将单词边界锚点应用于单个正则表达式中的所有标记
Apply a word-boundary anchor to all tokens in a single regex
假设我有一个要在字符串中匹配的标记列表: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
您可以使用非捕获组并添加标记。
使用 /g
全局标志匹配所有匹配项。然后使用 replace 将匹配项替换为您的替换值。
var str = "john, jack, heather, wheather, hijack, johnny";
var res = str.replace(/\b(?:john|jack|heather)\b/g, "test");
console.log(res);
假设我有一个要在字符串中匹配的标记列表: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
您可以使用非捕获组并添加标记。
使用 /g
全局标志匹配所有匹配项。然后使用 replace 将匹配项替换为您的替换值。
var str = "john, jack, heather, wheather, hijack, johnny";
var res = str.replace(/\b(?:john|jack|heather)\b/g, "test");
console.log(res);