简体   繁体   中英

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.

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, - a literal sunstring BRDA:2,
    • \\d+ - 1 or more digits
    • , - a comma
    • \\d+, - 1+ digits and a comma
  • \\d+ - 1+ digits.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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