.net - C# dollar problem with regex-replace -


i want insert dollar sign @ specific position between 2 named capturing groups. problem means 2 following dollar-signs in replacement-string results in problems.

how able directly replace-method? found workaround adding temporary garbage instantly remove again.

see code problem:

      // want add dollar sign before number , use named groups capturing;       // varying parts of strings in brackets []       // [somebody] has [some-dollar-amount] in [something]        string joehas = "joe has 500 in wallet.";       string jackhas = "jack has 500 in pocket.";       string jimhas = "jim has 740 in bag.";       string jasonhas = "jason has 900 in car.";        regex dollarinsertion = new regex(@"(?<start>^.*? has )(?<end>\d+ in .*?$)", regexoptions.multiline);        console.writeline(joehas);       console.writeline(jackhas);       console.writeline(jimhas);        console.writeline(jasonhas);       console.writeline("--------------------------");        joehas = dollarinsertion.replace(joehas, @"${start}$${end}");       jackhas = dollarinsertion.replace(jackhas, @"${start}$-${end}");                 jimhas = dollarinsertion.replace(jimhas, @"${start}\$${end}");       jasonhas = dollarinsertion.replace(jasonhas, @"${start}$kkkkkk----kkkk${end}").replace("kkkkkk----kkkk", "");        console.writeline(joehas);       console.writeline(jackhas);       console.writeline(jimhas);       console.writeline(jasonhas);     output: joe has 500 in wallet. jack has 500 in pocket. jim has 740 in bag. jason has 900 in car. -------------------------- joe has ${end} jack has $-500 in pocket. jim has \${end} jason has $900 in car. 

use replacement pattern: "${start}$$${end}"

the double $$ escapes $ treated literal character. third $ part of named group ${end}. can read on msdn substitutions page.

i stick above approach. alternately can use replace overload accepts matchevaluator , concatenate need, similar following:

jackhas = dollarinsertion.replace(jackhas,               m => m.groups["start"].value + "$" + m.groups["end"].value); 

Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

400 Bad Request on Apache/PHP AddHandler wrapper -

php - Change action and image src url's with jQuery -