1

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}

0

2 Answers 2

5

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); }; 
Sign up to request clarification or add additional context in comments.

4 Comments

Not far off corerct, you just need var result = Regex.Replace(input, and then your other two parameters. And you need Groups[2] as Groups[0] is the whole match, not the first group.
Thank you for answer. In my program I must to ask to user two rules: 1. For search. 2. For replacing. It can be different rules, not static. At other situation it can be other changing rule
ReplaceFunction it is fixed in a code, but user must to has capability for set rule for search, and rule for changing via strings manually.
then your can add a formula evaluator with another input. here is a nice example: jarloo.com/c-formula-evaluator not so fast, but its a very good idea
1
string input = @"Position 10"; string output = Regex.Replace(input, "^Position ([0-9]+)$", match => "Position " + Int32.Parse(match.Groups[1].Value) + 5); 

1 Comment

The lambda expression is fixed in a code, but user must to has capability for set rule for search, and rule for changing via strings manually.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.