1

给定一个包含 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)。

4

1 回答 1

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))));
于 2013-07-28T23:49:09.023 回答