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);
- 如果字符串始终以 # 开头,那就太好了,但事实并非如此。
- 然后我尝试了这个
/(#?\b${userStr})\b/
,但如果字符串确实以 #
开头,它会尝试匹配 ##hello
.
matchThis
str 可以是数组中 3 个示例中的任何一个,userStr 可能包含 matchThis
的多个变体,但只有一个是准确的
检查关键字是否已经以特殊字符开头。如果是,请不要将其包含在正则表达式中。
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,则匹配失败的否定前瞻。
我正在查找字符串中的关键字匹配项。我正在尝试使用单词边界,但这可能不是该解决方案的最佳案例。关键字可以是任何单词,并且可以以非单词字符开头。该字符串可以是任何字符串,并且可以在数组中包含所有这三个词,但我应该只匹配关键字:
['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);
- 如果字符串始终以 # 开头,那就太好了,但事实并非如此。
- 然后我尝试了这个
/(#?\b${userStr})\b/
,但如果字符串确实以#
开头,它会尝试匹配##hello
. matchThis
str 可以是数组中 3 个示例中的任何一个,userStr 可能包含matchThis
的多个变体,但只有一个是准确的
检查关键字是否已经以特殊字符开头。如果是,请不要将其包含在正则表达式中。
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,则匹配失败的否定前瞻。