views:

220

answers:

1

I want to replace all double tokens in string with the double value appended with "c" letter. Is there an easy way to do it? I thought that the Regular Expression is the way to go

for example, I wanna change the following

treand60(12.3)/1010 + 1 >1010

with

treand60(12.3c)/1010c + 1c >123c

any suggestions

+1  A: 

Basically you want to look for all sequences of digits optionally ending with a decimal point and another digit sequence and then append a 'c'. Here's an example, assuming you're using Perl (your question doesn't say):

$_ = 'treand60(12.3)/1010 + 1 >1010';
s/\b\d+(?:\.\d+)?/$&c/g;
print;  # output is "treand60(12.3c)/1010c + 1c >1010c"

\d+ is 1 or more digit and then \.\d+ is 1 or more digit after a decimal point. The (?: ... ) is a non-capturing group. The last ? means "match zero or one of these" (i.e. it's optional). And the \b means match only on word boundaries (this prevents something like "Hello123" from matching because the number comes directly after a word character).

Here is the C# equivalent:

using System.Text.RegularExpressions;
// ...

string input = "treand60(12.3)/1010 + 1 >1010";
Regex regex = new Regex(@"\b\d+(?:\.\d+)?");
string output = regex.Replace(input, (m) => m.Value + 'c');
Console.WriteLine(output);  // prints "treand60(12.3c)/1010c + 1c >1010c"

The lambda expression inside the Regex.Replace call is a MatchEvaluator which simply gets the match text and appends a 'c'.

bobbymcr
Sorry I didnt mention that I wanna do it with C#
Mustafa A. Jabbar
Check my update.
bobbymcr
that works perfectly, thank you
Mustafa A. Jabbar