加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 06:33:21 所属栏目:百科 来源:网络整理
导读:我正在尝试获得一个正则表达式替换工作来更新我的AssemblyInfo.cs文件,所以我有: Regex.Replace( contents,@"([assembly: Assembly(File)?Version("").*("")])","$1" + version + "$3"); 问题是该版本是类似“1.5.3.0”,所以当替换被评估时,它看到“
我正在尝试获得一个正则表达式替换工作来更新我的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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读