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

标签 .net regex

我正在尝试使用正则表达式替换来更新我的 AssemblyInfo.cs 文件,所以我有:

Regex.Replace(
    contents, 
    @"(\[assembly: Assembly(File)?Version\("").*(""\)\])", 
    "$1" + version + "$3"
);

问题是 version 类似于 "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

此行为已明确记录:

Regular Expression Language Elements - Substitutions

Substituting a Numbered Group

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.

Substituting a Named Group

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.

关于.net - 正则表达式替换捕获后跟数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3466892/

相关文章:

c# - 我如何验证 wpf 绑定(bind)是否会转到真实属性?

c# - 寻找一些 UI 线程和工作线程教程

regex - 狂欢 : regular expressions within backticks

javascript - 正则表达式不匹配 6 个重复的数字

regex - 完全重定向所有网址,只需更改域名

c# - 使用 C# 进行语音转文本

c# - 在可以修改的类上使用扩展方法是否可以接受

php - 你能告诉我这个正则表达式是什么意思吗?

javascript - 使用正则表达式进行算术

c# - 无法加载文件或程序集 'PayPalAdaptivePaymentsSDK,版本 = 2.12.117.0