在执行Regex.Replace时如何使用命名捕获?我已经做到了这一点,它做了我想要的但不是我想要的方式:
[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);
}
Run Code Online (Sandbox Code Playgroud)
我希望将这两个单词与命名的捕获匹配,然后在执行替换时使用(命名)捕获.
Caf*_*eek 12
只需更换 ${groupName}
[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, "${secondMatch} ${firstMatch}");
Assert.AreEqual(expected, replace);
}
Run Code Online (Sandbox Code Playgroud)