简体   繁体   English

正则表达式替换捕获,后跟数字

[英]Regex replacement capture followed by digit

I am trying to get a Regex replacement working to update my AssemblyInfo.cs files, so I have: 我正在尝试使用正则表达式替换来更新我的AssemblyInfo.cs文件,所以我有:

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

The problem is that version is something like "1.5.3.0" , so that when the replacement is evaluated it is seeing "$11.5.3.0$3" and is presumably looking for the eleventh captured group because it is coming out with: 问题是version类似于"1.5.3.0" ,因此在评估替换version时,它看到的是"$11.5.3.0$3" ,并且大概是在寻找第十一个捕获的组,因为它的输出是:

$11.5.3.0")]

If is stick a space after the $1 it works fine. 如果在$1之后留一个空格,它将正常工作。 What do I need to put in there to escape the second digit without actually inserting the character? 在不实际插入字符的情况下,我需要放入哪里以转义第二个数字?

Use ${1} instead of $1 . 使用${1}代替$1 This is also the substitution syntax for named capturing group (?<name>) . 这也是命名捕获组 (?<name>)的替代语法。

Here's a snippet to illustrate ( see also on ideone.com ): 这是一个片段说明( 也请参见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

This behavior is explicitly documented: 此行为已明确记录:

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. $number语言元素包括替换字符串中与number捕获组匹配的最后一个子字符串,其中number是捕获组的索引。

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. 如果number未指定在正则表达式模式中定义的有效捕获组,则$number被解释为文字字符序列 ,用于替换每个匹配项。

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. ${name}语言元素替换由name捕获组匹配的最后一个子字符串,其中name是由(?<name>)语言元素定义的捕获组的(?<name>)

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. 如果name未指定在正则表达式模式中定义的有效的命名捕获组,则${name}被解释为文字字符序列 ,用于替换每个匹配项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM