1

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

1

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.