说我有一个我想在字符串中匹配的标记列表:tok1,tok2,tok3等等......
我希望在单个正则表达式中将单词边界应用于所有这些,但每次都不会复制粘贴\b
。这是我要避免的:
/\btok1\b|\btok2\b|\btok3\b|\btok4\b|\btok5\b/g
我试过了:
/\b(str1|str2|str3|str4|str5)\b/g
但是使用javascript .replace()
方法无效。
是否有另一种方法可以将单词边界锚点应用于单个正则表达式中的所有标记?
---编辑:---
正则表达式的例子我试图分解:
/\bjohn\b|\bjack\b|\bheather\b/g
预期结果:
john //match
jack //match
heather //match
wheather //not match
hijack //not match
johnny //not match
答案 0 :(得分:1)
您可以使用非捕获组并添加令牌。
使用/g
全局标记来匹配所有匹配项。然后使用replace将替换值替换为匹配值。
var str = "john, jack, heather, wheather, hijack, johnny";
var res = str.replace(/\b(?:john|jack|heather)\b/g, "test");
console.log(res);