Michael Rafailyk
Michael Rafailyk

Reputation: 462

How to replace every comma inside round brackets with regexp

I have a string:

"a: a(1, 2, 3), b: b(1, 2)"

Need to replace every , inside round brackets with a _. I expect to see:

"a: a(1_ 2_ 3), b: b(1_ 2)"

Now i use it but only first comma in a brackets is replaced, not all:

let string = "a: a(1, 2, 3), b: b(1, 2)";
string = string.replace(/(\()([\d\.\-\s]+)(\,)([\d\.\-\s]+)(\))/g, '$1$2_$4$5');

// a: a(1_ 2, 3), b: b(1_ 2)

Upvotes: 1

Views: 1467

Answers (2)

anubhava
anubhava

Reputation: 785008

You may use a lookahead based regex:

str = str.replace(/,(?=[^()]*\))/g, '$&_')

RegEx Demo

var str = "a: a(1, 2, 3), b: b(1, 2)"
str = str.replace(/,(?=[^()]*\))/g, '$&_')
console.log(str)

RegEx Details:

  • ,: match a comma
  • (?=[^()]*\)): Positive Lookahead to assert that we don't have a closing ) before matching any ( or ) in between
  • $&_: $& is back-reference of the full match and we append a literal _ at the end

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521028

We could use a regex replacement with a callback function:

var input = "a: a(1, 2, 3), b: b(1, 2)";
var output = input.replace(/\(\d+(?:, \d+)*\)/g, (match, startIndex, wholeString) => {
    return match.replace(/,/g, "_");
});
console.log(input);
console.log(output);

The idea here is to match each tuple using the following regex pattern:

\(\d+(?:, \d+)*\)

Then, we pass each match to the callback function which then does a global replacement on , to replace with _.

Upvotes: 2

Related Questions