正则表达式替换捕获后按数字 [英] Regex replacement capture followed by digit
问题描述
我想获得一个正则表达式替换工作更新我的AssemblyInfo.cs文件,所以我有:
I am trying to get a Regex replacement working to update my AssemblyInfo.cs files, so I have:
Regex.Replace(
contents,
@"(\[assembly: Assembly(File)?Version\("").*(""\)\])",
"$1" + version + "$3"
);
问题是,版本
是像1.5.3.0
,这样当更换评估这是一个看$ 11.5.3.0 $ 3
是presumably寻找十一届捕获组,因为它是走出来:
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:
$11.5.3.0")]
如果是后 $ 1棒的空间
它工作正常。需要什么就摆在那里逃脱的第二位,而不实际插入字符?
If is stick a space after the $1
it works fine. What do I need to put in there to escape the second digit without actually inserting the character?
推荐答案
使用 $ {1}
而不是 $ 1
。这也是名为捕获组的替换语法 (小于?;名称>)
Use ${1}
instead of $1
. This is also the substitution syntax for named capturing group (?<name>)
.
下面是一个片段来说明(另见ideone.com ):
Here's a snippet to illustrate (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
此行为被明确记载:
This behavior is explicitly documented:
在 $号
语言元素,包括所匹配的号码的后子
捕获组在替换字符串,其中号
是捕获组的索引。
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.
如果号
没有指定在常规EX pression模式定义的有效捕获组, $号
是PTED为跨$ P $一个的文字字符序列的用于替换每个匹配。
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.
在 $ {名}
语言元素替换匹配的名称
捕获组,其中<$的最后一个子C $ C>名称是由定义的捕获组的名称(LT;名称&gt;)
语言元素
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.
如果名称
没有指定在常规EX pression模式定义了一个有效的命名捕获组, $ {名}
是PTED为的文字字符序列的用于替换每个匹配。
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.
这篇关于正则表达式替换捕获后按数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!