正则表达式用于替换包含数字的组

时间:2016-05-10 16:01:46

标签: c# regex

关于可能的重复帖子:Replace only some groups with Regex

这不是骗局,因为帖子用静态文本替换了组,我想要的是通过保留组中的文本来替换组。

我有一些文字包含如下模式:

\super 1 \nosupersub
\super 2 \nosupersub
...
\super 592 \nosupersub

我想用正则表达式替换它们,使它们成为:

<sup>1</sup>
<sup>2</sup>
...
<sup>592</sup>

所以,我使用以下正则表达式(注意组(\d+)):

RegexOptions options = RegexOptions.Multiline; //as of v1.3.1.0 default is multiline
mytext = Regex.Replace(mytext, @"\s?\\super\s?(\d+)\s?\\nosupersub\s", @"<sup>\1</sup>", options);

然而,我没有得到我想要的东西,而是将所有结果替换为<sup>\1</sup>

<sup>\1</sup>
<sup>\1</sup>
...
<sup>\1</sup>

如果我尝试使用https://www.sublimetext.com等文本编辑器并使用Python替换正则表达式,则可以。

如何在(\d+)中更换C#这样的组{保留号码?

2 个答案:

答案 0 :(得分:2)

许多正则表达式工具使用\1表示法来指代替换模式中的组值(语法与反向引用相同)。无论出于何种原因,Microsoft选择使用$1作为正则表达式.NET实现中的表示法。请注意,反向引用仍然使用.NET中的\1语法。它只是替换模式中的语法不同。有关详细信息,请参阅this page替换部分。

答案 1 :(得分:1)

我没有测试过这段代码,并且是从内存中写的,所以这可能不起作用,但总体思路就在那里。

为什么要使用正则表达式?

List<string> output = new List<string>();
foreach (string line in myText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
    string alteredLine = line.Replace("\super", "").Replace("\nosupersub", "").Trim();

    int n;
    if (Int32.TryParse(alteredLine, out n))
    {
        output.Add("<sup>" + n + "</sup>");
    }
    else
    {
         //Add the original input in case it failed?
         output.Add(line);
    }
}

或linq版本:

myText = myText.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
               .Select(l => "<sup>" + l.Replace("\super", "").Replace("\nosupersub", "").Trim() + "</sup>");