开发者

Regex replace all function

开发者 https://www.devze.com 2023-04-04 00:06 出处:网络
I have following example string: $0$aaaaa$1$bbbbb$2$cccccc where between dollar markers there are some numbers. I would like to use Regex to replace each number by number + 1, so the output should be:

I have following example string:

$0$aaaaa$1$bbbbb$2$cccccc

where between dollar markers there are some numbers. I would like to use Regex to replace each number by number + 1, so the output should be:

$1$aaaaa$2$bbbbb$3$cccccc

How can I do this using Regex in C#?

I know how to find all the numbers:

string s = "$0$aaaaa$1$bbbbb$2$cccccc";
Regex regex = new Regex(@"\$(?<myNumber>.*?)\$");

MatchCollection matches = regex.Matches(s);

foreach (Match match in matches)
{
    Console.WriteLine(match.Groups["myNumber"]);
}

Console.WriteLine("\n\nFinal string = " + s);
Console.ReadKey();

By regex.Replace(...) I can replace them all by one开发者_开发知识库 value, but I have no idea how to replace each number individually with regex.

Does anyone know how to do that?

Best regards,

Marcin


var result = Regex
    .Replace(input, @"(?<=\$)\d+(?=\$)", m => (int.Parse(m.Value) + 1).ToString());
0

精彩评论

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