javascript - 如何用正则表达式替换圆括号内的每个逗号
问题描述
我有一个字符串:
"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)
解决方案
我们可以使用带有回调函数的正则表达式替换:
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+)*\)
然后,我们将每个匹配项传递给回调函数,该回调函数然后进行全局替换,
以替换为_
。
推荐阅读
- php - 为什么 aws-sdk-php 3 除了一般异常之外,还删除了 DynamoDb 异常?
- matlab - 通过一些 3D 点拟合一条线
- php - WooCommerce 从订单中获取状态已付款或免费跟踪
- weighted-average - If else 和 if 加权平均
- javascript - 自动清除多个输入字段
- flutter - 在颤动中更改滑块的拇指颜色
- php - 为什么 laravel 不监听端口,但在部署生产时表达需要?
- google-sheets - 多个条件下多个值求和的迭代公式
- apache-kafka - kafka - S3接收器连接器 - 没有找到辅助解串器
- swift - 在 Swift 中使用 Codable 解析 JSON 数据