Javascript 带有可选非单词字符的正则表达式单词边界

Javascript Regex Word Boundary with optional non-word character

我正在查找字符串中的关键字匹配项。我正在尝试使用单词边界,但这可能不是该解决方案的最佳案例。关键字可以是任何单词,并且可以以非单词字符开头。该字符串可以是任何字符串,并且可以在数组中包含所有这三个词,但我应该只匹配关键字:

['hello', '#hello', '@hello'];

这是我的代码,其中包括在 post:

中发现的尝试
let userStr = 'why hello there, or should I say #hello there?';

let keyword = '#hello';

let re = new RegExp(`/(#\b${userStr})\b/`);

re.exec(keyword);

检查关键字是否已经以特殊字符开头。如果是,请不要将其包含在正则表达式中。

var re;
if ("#@".indexOf(keyword[0]) == -1) {
    re = new RegExp(`[@#]?\b${keyword}\b`);
} else {
    re = new RegExp(`\b${keyword}\b`);
}

这里你需要考虑三件事:

  • 要点是 \b 词边界是上下文相关的构造,如果您的输入不总是纯字母数字,则需要明确的词边界
  • 您需要在构造函数 RegExp 表示法中双重转义特殊字符
  • 当您将变量传递给正则表达式时,您需要确保所有特殊字符都已正确转义。

使用

let userStr = 'why hello there, or should I say #hello there?';
let keyword = '#hello';
let re_pattern = `(?:^|\W)(${keyword.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&')})(?!\w)`;
let res = [], m;

// To find a single (first) match
console.log((m=new RegExp(re_pattern).exec(userStr)) ? m[1] : "");

// To find multiple matches:
let rx = new RegExp(re_pattern, "g");
while (m=rx.exec(userStr)) {
    res.push(m[1]);
}
console.log(res);

模式说明

  • (?:^|\W) - 匹配字符串开头或任何非单词字符的非捕获字符串
  • (${keyword.replace(/[-\/\^$*+?.()|[\]{}]/g, '\$&')}) - 第 1 组:具有转义特殊字符的 关键字
  • (?!\w) - 如果当前位置右侧紧邻单词 char,则匹配失败的否定前瞻。