执行 Regex.Replace() 时如何使用命名组 [英] How to use named groups when performing a Regex.Replace()
问题描述
在执行 Regex.Replace 时如何使用命名捕获?我已经走了这么远,它做了我想要的但不是我想要的方式:
How do I use named captures when performing Regex.Replace? I have gotten this far and it does what I want but not in the way I want it:
[TestCase("First Second", "Second First")]
public void NumberedReplaceTest(string input, string expected)
{
Regex regex = new Regex("(?<firstMatch>First) (?<secondMatch>Second)");
Assert.IsTrue(regex.IsMatch(input));
string replace = regex.Replace(input, "$2 $1");
Assert.AreEqual(expected, replace);
}
我想用命名捕获匹配这两个词,然后在执行替换时使用(命名)捕获.
I want to match the two words with named captures and then use the (named) captures when performing the replace.
推荐答案
代替 "$2 $1"
,你可以使用 "${secondMatch} ${firstMatch}"
>.
Instead of "$2 $1"
, you can use "${secondMatch} ${firstMatch}"
.
此处列出了您可以执行的所有替换操作.
There is a list of all the replacements you can do here.
这是一个简短的列表:
$number - 按编号捕获的组.
$number - The captured group by number.
${name} - 按名称捕获的组.
${name} - The captured group by name.
$$ - $ 文字.
$& - 整场比赛.
$` - 匹配前的输入字符串.
$` - The input string before the match.
$' - 匹配后的输入字符串.
$' - The input string after the match.
$+ - 捕获的最后一组.
$+ - The last group captured.
$_ - 整个输入字符串.
$_ - The entire input string.
这篇关于执行 Regex.Replace() 时如何使用命名组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!