C# 执行 Regex.Replace() 时如何使用命名组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12962114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:07:16  来源:igfitidea点击:

How to use named groups when performing a Regex.Replace()

c#regexreplace

提问by Johan Larsson

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:

执行 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, " ");
    Assert.AreEqual(expected, replace);
}

I want to match the two words with named captures and then use the (named) captures when performing the replace.

我想将这两个词与命名捕获匹配,然后在执行替换时使用(命名)捕获。

采纳答案by Kendall Frey

Instead of "$2 $1", you can use "${secondMatch} ${firstMatch}".

相反"$2 $1",您可以使用"${secondMatch} ${firstMatch}".

There is a list of all the replacements you can do here.

此处列出了您可以执行的所有替换操作。

Here is an abbreviated list:

这是一个简短的列表:

$number- The captured group by number.

$number- 按编号捕获的组。

${name}- The captured group by name.

${name}- 按名称捕获的组。

$$- $ literal.

$$- $ 字面量。

$&- Entire match.

$&- 整个比赛。

$`- The input string before the match.

$`- 匹配前的输入字符串。

$'- The input string after the match.

$'- 匹配后的输入字符串。

$+- The last group captured.

$+- 捕获的最后一组。

$_- The entire input string.

$_- 整个输入字符串。

回答by CaffGeek

Simply replace with ${groupName}

简单地替换为 ${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);
}