简体   繁体   English

使用正则表达式替换匹配字符串的最后一个字符

[英]Replace last character of a matched string using regex

I am need to post-process lines in a file by replacing the last character of string matching a certain pattern. 我需要通过替换匹配特定模式的字符串的最后一个字符来对文件中的行进行后处理。

The string in question is: 有问题的字符串是:

BRDA:2,1,0,0

I'd like to replace the last digit from 0 to 1. The second and third digits are variable, but the string will always start BRDA:2 that I want to affect. 我想将最后一位数字从0替换为1.第二位和第三位是可变的,但字符串将始终启动我想要影响的BRDA:2。

I know I can match the entire string using regex like so 我知道我可以使用正则表达式来匹配整个字符串

/BRDA:2,\d,\d,1

How would I get at that last digit for performing a replace on? 我如何获得最后一个数字来执行替换?

Thanks 谢谢

You may match and capture the parts of the string with capturing groups to be able to restore those parts in the replacement result later with backreferences . 您可以使用捕获组匹配和捕获字符串的各个部分,以便稍后可以使用反向引用在替换结果中恢复这些部分。 What you need to replace/remove should be just matched. 你需要更换/删除的东西应该匹配。

So, use 所以,使用

 var s = "BRDA:2,1,0,0" s = s.replace(/(BRDA:2,\\d+,\\d+,)\\d+/, "$11") console.log(s) 

If you need to match the whole string you also need to wrap the pattern with ^ and $ : 如果你需要匹配整个字符串,你还需要用^$包装模式:

s = s.replace(/^(BRDA:2,\d+,\d+,)\d+$/, "$11")

Details : 细节

  • ^ - a start of string anchor ^ - 字符串锚点的开始
  • (BRDA:2,\\d+,\\d+,) - Capturing group #1 matching: (BRDA:2,\\d+,\\d+,) - 捕获组#1匹配:
    • BRDA:2, - a literal sunstring BRDA:2, BRDA:2, - 字面意思是BRDA:2,
    • \\d+ - 1 or more digits \\d+ - 1位或更多位数
    • , - a comma , - 一个逗号
    • \\d+, - 1+ digits and a comma \\d+, - 1+位数和逗号
  • \\d+ - 1+ digits. \\d+ - 1+位数。

The replacement - $11 - is parsed by the JS regex engine as the $1 backreference to the value kept inside Group 1 and a 1 digit. 替换 - $11 - 由JS正则表达式引擎解析为$1反向引用保持在第1组和1位数内的值。

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

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