C # Regex - match and replace, auto grow

I am working with a problem and any help would be greatly appreciated.

Problem: I have a paragraph, and I want to replace a variable that appears several times (Variable = @Variable). This is the easy part, but the part I'm having difficulty with is trying to replace the variable with different values.

I need each event to have a different meaning. For example, I have a function that calculates for each variable. What I'm still below:

private string SetVariables(string input, string pattern){ Regex rx = new Regex(pattern); MatchCollection matches = rx.Matches(input); int i = 1; if(matches.Count > 0) { foreach(Match match in matches) { rx.Replace(match.ToString(), getReplacementNumber(i)); i++ } } 

I can replace every variable I need with the number returned by getReplacementNumber (i), but how did I get it back to the original input with the replaced values ​​in the same order as in the match collection

Thanks in advance!

Mark

+6
source share
1 answer

Use the Replace overload, which takes a MatchEvaluator as the second parameter.

 string result = rx.Replace(input, match => { return getReplacementNumber(i++); }); 

I assume getReplacementNumber(int i) returns a string . If not, you need to convert the result to a string.

See how it works on the Internet: ideone

+8
source

Source: https://habr.com/ru/post/918218/


All Articles