我期望来自 HTML 输入框的一串数字,但我正在寻找一个正则表达式,以便我可以捕获字符串的某些部分并将其替换为某些内容,现在我想要的是,对于下一次迭代,正则表达式应该跳过其中的部分已处理完毕。
看看我的正则表达式
string.replace(/([\d]{10})/gm, "$1,")
迭代的预期结果
- 895645784578457845784578457845
来源
- 8956457845,7845784578,4578457845,9089
即将提供更多数据
但问题就是结果
- 8956457845,7845784578,4578457845
- 8956457845,,,7845784578,,,4578457845,,,9089
最佳答案
如果我理解正确,您希望像 string.replace(\regex\, '$1,').replace(\regex\, '$1,' 一样递归地对一个数字字符串应用 regex-replace ).replace(\regex\, '$1,')
,但忽略了已经替换的部分。
下面是一种使用负向预测的解决方案。
let test = '895645784578457845784578457845' //org string
let test1 = test.replace(/(\d{10}(?!\,))/gm, "$1,")
.replace(/(\d{10}(?!\,))/gm, "$1,")
.replace(/(\d{10}(?!\,))/gm, "$1,")
// simulate recurse-replace three times
console.log(test1)
test1 += '1234567890123' //new string came
let test2 = test1.replace(/(\d{10}(?!\,))/gm, "$1,")
console.log(test2)
test2 += '1234567890123' //new string came
let test3 = test2.replace(/(\d{10}(?!\,))/gm, "$1,")
console.log(test3)
关于javascript - 替换后,跳过字符串的该部分 - Regex Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52170794/