[英]C# Regex - Match and replace, Auto Increment
I have been toiling with a problem and any help would be appreciated. 我一直在努力解决问题,任何帮助将不胜感激。
Problem: I have a paragraph and I want to replace a variable which appears several times (Variable = @Variable). 问题:我有一个段落,我想要替换多次出现的变量(变量= @Variable)。 This is the easy part, but the portion which I am having difficulty is trying to replace the variable with different values.
这是一个简单的部分,但我遇到困难的部分是尝试用不同的值替换变量。
I need for each occurrence to have a different value. 我需要每次出现都有不同的值。 For instance, I have a function that does a calculation for each variable.
例如,我有一个函数可以对每个变量进行计算。 What I have thus far is 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 am able to replace each variable that I need to with the number returned from getReplacementNumber(i) function, but how to I put it back into my original input with the replaced values, in the same order found in the match collection? 我可以用getReplacementNumber(i)函数返回的数字替换我需要的每个变量,但是如何用匹配集合中找到的相同顺序将它放回到我的原始输入中的替换值?
Thanks in advance! 提前致谢!
Marcus 马库斯
Use the overload of Replace
that takes a MatchEvaluator
as its second parameter. 使用
Replace
的重载, Replace
MatchEvaluator
作为其第二个参数。
string result = rx.Replace(input, match => { return getReplacementNumber(i++); });
I'm assuming here that getReplacementNumber(int i)
returns a string
. 我假设
getReplacementNumber(int i)
返回一个string
。 If not, you will have to convert the result to a string. 如果没有,您将必须将结果转换为字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.