开发者

Using RegEx to find and replace doubles

开发者 https://www.devze.com 2022-12-13 04:20 出处:网络
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

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 >12开发者_如何学JAVA3c

any suggestions


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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消