我正在尝试使用正则表达式替换来更新我的 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 thenumber
capturing group in the replacement string, wherenumber
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 thename
capturing group, wherename
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/