首页 > 解决方案 > 如何用正则表达式替换圆括号内的每个逗号

问题描述

我有一个字符串:

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

需要用 . 替换每个,内部圆括号_。我希望看到:

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

现在我使用它,但只替换括号中的第一个逗号,而不是全部:

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)

标签: javascriptregexreplace

解决方案


我们可以使用带有回调函数的正则表达式替换:

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);

这里的想法是使用以下正则表达式模式匹配每个元组:

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

然后,我们将每个匹配项传递给回调函数,该回调函数然后进行全局替换,以替换为_


推荐阅读