Andrey Bushman
Andrey Bushman

Reputation: 12506

Math expression on Regex expression

I have many text rows, and I must find some rows, and to change them.

I wrote such regex rule:

^(Position) ([0-9]+)$

For example, I must find all such rows:

Position 10
Position 11
Position 12

Now I must increase numbers at 5. How can I do it through Regex? I try to wrote such regex rule:

$1 {$2+ 5}

I need get result:

Position 15
Position 16
Position 17

But I have got:

Position {10 +5}
Position {11+5}
Position {12+5}

Upvotes: 1

Views: 795

Answers (2)

user287107
user287107

Reputation: 9417

the Regex Replace function takes either a string, or a function. you used the string replacement, so just the string is inserted. if you want an integer operation, you need to use the replace with function method.

http://msdn.microsoft.com/library/cft8645c(v=vs.80).aspx

this code is not correct, it should just show the way how it could be done

 Regex.Replace("^(Position) ([0-9]+)$", ReplaceFunction);


 public string ReplaceFunction(Match m)  { return "Position " + (int.Parse(m.Groups[2].Value) + 5); };

Upvotes: 5

aquinas
aquinas

Reputation: 23796

string input = @"Position 10";
string output = Regex.Replace(input, "^Position ([0-9]+)$", match => "Position " + Int32.Parse(match.Groups[1].Value) + 5);

Upvotes: 1

Related Questions