给定一个输入字符串,我需要查找并替换它:
funccall(x, y, z, w)
这样:
call(x, y, 0, z, w)
逗号之间以及逗号和括号之间的所有内容都是未知的(即,每个输入可能不同)。这包括 x、y、z 和 w 的值,以及之间的空格量。
但是 funccall
部分是不变的(即,这是我应该寻找的实际子字符串),并且我需要在第二个逗号之后插入 0,
的事实也是不变的。
这是我的方法:
function fix(str) {
const index0 = str.indexOf('funccall');
if (index0 >= 0) {
const index1 = str.indexOf(',', str.indexOf(',', index0) + 1);
const part0 = str.substring(0, index0);
const part1 = str.substring(index0 + 'func'.length, index1) + ', 0';
const part2 = str.substring(index1);
return part0 + part1 + part2;
}
return str;
}
我真的希望有一个单行解决方案(或者至少是接近单行的解决方案)。
最佳答案
如果您可以指望输入字符串在参数分隔符之外不包含逗号,则可以使用正则表达式 - 匹配 x, y,
部分和 z, w
部分,并在中间放置 0,
:
const fix = str => str.replace(
/(funccall\((?:[^,]+,){2})([^,]+,[^,]+\))/g,
(_, g1, g2) => `${g1} 0,${g2}`
);
console.log(fix('funccall(x, y, z, w)'));
该模式由 2 组组成:
(funccall\((?:[^,]+,){2})
:funccall\(
- 匹配funccall
后跟(
(?:[^,]+,){2})
- 匹配(除逗号之外的任何内容,后跟逗号)两次
([^,]+,[^,]+\))
:([^,]+,
- 匹配除逗号之外的任何内容,后跟逗号[^,]+
- 后跟除逗号之外的任何内容(最后一个参数没有尾随 逗号)\)
- 后跟)
关于javascript - Javascript 中的查找/替换任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56788256/