.net – 正则表达式替换捕获后跟数字

前端之家收集整理的这篇文章主要介绍了.net – 正则表达式替换捕获后跟数字前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试获得一个正则表达式替换工作来更新我的AssemblyInfo.cs文件,所以我有:
Regex.Replace(
    contents,@"(\[assembly: Assembly(File)?Version\("").*(""\)\])","$1" + version + "$3"
);

问题是该版本是类似“1.5.3.0”,所以当替换被评估时,它看到“$ 11.5.3.0 $ 3”,并且可能是寻找第十一个捕获的组,因为它出来了:

$11.5.3.0")]

如果在$ 1之后粘贴一个空格,它可以正常工作。我需要放在哪里才能摆脱第二个数字而不插入字符?

使用$ {1}而不是$ 1。这也是名为 capturing group(?< name>)的替代语法。

这是一个说明的代码片段(see also on ideone.com):

Console.WriteLine(Regex.Replace("abc","(.)","$11"));        // $11$11$11
Console.WriteLine(Regex.Replace("abc","${1}1"));      // a1b1c1
Console.WriteLine(Regex.Replace("abc","(?<x>.)","${x}1"));  // a1b1c1

此行为明确记录:

07002 – 07003

07004

The $number language element includes the last substring matched by the number capturing group in the replacement string,where number is the index of the capturing group.

If number does not specify a valid capturing group defined in the regular expression pattern,$number is interpreted as a literal character sequence that is used to replace each match.

07005

The ${name} language element substitutes the last substring matched by the name capturing group,where name is the name of a capturing group defined by the (?<name>) language element.

If name does not specify a valid named capturing group defined in the regular expression pattern,${name} is interpreted as a literal character sequence that is used to replace each match.

原文链接:https://www.f2er.com/regex/357376.html

猜你在找的正则表达式相关文章