[英]JS Regex - Replace multiple instances in a string
I have this string: 我有这个字符串:
var str = '"testFN, II testLN, II" < test1@test.com>, "testFN, Cal testLN, Cal" < test2@test.com>';
and I am doing 我在做
str.replace(/(".*?),(.*?")/g, '$1__comma_$2');
to replace multiple commas(,) with in a string(__comma_), only inside "". 仅在“”内用字符串(__comma_)替换多个逗号(,)。
Event though I given /g its not replacing the all instances. 事件虽然我给/ g它不替换所有实例。 It replace only first match of each instance. 它仅替换每个实例的第一个匹配项。
Actual Result: "testFN__comma_ II testLN, II" < test1@test.com>, "testFN__comma_ testLN, Cal" < test2@test.com> Expected Result: "testFN__comma_ II testLN__comma_ II" < test1@test.com>, "testFN__comma_ Cal testLN__comma_ Cal" < test2@test.com> 实际结果:“ testFN__comma_ II testLN,II” <test1@test.com>,“ testFN__comma_ testLN,Cal” <test2@test.com>预期结果:“ testFN__comma_ II testLN__comma_ II” <test1@test.com>,“ testFN__comma_ Cal testLN__comma_ Cal“ <test2@test.com>
Can you please give any suggestions that I am missing anything ? 你能给我一些什么我想念的建议吗?
Try lazy quantifier: 尝试延迟量词:
(".*?,)(.*?")
However your replacements wouldn't take effect as you are not replacing that comma! 但是,由于您没有替换逗号,因此替换将不会生效! So I'm going to modify your regex a little bit: 因此,我将对您的正则表达式进行一些修改:
(".*?),(.*?")
Based on your new update, I made another regex which is totally different from previous one. 根据您的新更新,我做了另一个与以前的正则表达式完全不同的正则表达式。
str.replace(/(,)(?=[^"]*[^\s]")/g, '__comma_');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.