使用C#的正则表达式:如何替换与特定组匹配的字符串

时间:2013-07-28 23:26:22

标签: c# regex

给出2组的正则表达式:

Regex regex = new Regex("^[^{}]*(\\{([^}]*)\\})[^{}]*$"); // group 1 matches {exp} (with braces)
                                                          // group 2 matches exp   (without braces)

如何替换第一组中的匹配?

string inputStr = "mystring{valueToRaplace}"
string s = regex .Replace(inputStr, m => ???);

例如,我想指定是否匹配并替换{valueToRaplace}(组1)或valueToRaplace(组2)。

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的

Regex regex = new Regex("^[^{}]*(\\{([^}]*)\\})[^{}]*$"); 
string inputStr = "mystring{valueToRaplace}";
string replaceWithThis = "Replace with this";

//change m.Groups[2] to whichever index you want to replace
string final = regex.Replace(inputStr, 
                    new MatchEvaluator(new Func<Match, string>(m => inputStr.Replace(m.Groups[2].Value, replaceWithThis))));