使用正则表达式在 javascript 中进行全词搜索

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18878143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:31:50  来源:igfitidea点击:

Whole word search in javascript using regex

javascript

提问by Nash3man

I'm trying to perform a whole word search in javascript using the following regex.

我正在尝试使用以下正则表达式在 javascript 中执行全词搜索。

str = "Test String C.S (example)";
var regex_search = new RegExp("\b"+search_string+"\b","g");
if(str.match(regex_search)) != null)
  match = true;
else
  match = false;

The above works well if I search for a normal string like 'String'. But if I search for just 'S', it returns C.S as a match. Also, searching for example returns a match but in this case I do not want a match because it has parenthesis. I just want to match the whole word only. Any suggestions would be greatly appreciated.

如果我搜索像“String”这样的普通字符串,上述方法效果很好。但是如果我只搜索“S”,它会返回 CS 作为匹配项。此外,搜索例如返回一个匹配,但在这种情况下我不想要一个匹配,因为它有括号。我只想匹配整个单词。任何建议将不胜感激。

--Edit--

- 编辑 -

Thanks to @plalx Clarified the example.

感谢@plalx 澄清了这个例子。

回答by progrenhard

Use capture groups?

使用捕获组?

.*?\b(S)

Regular expression visualization

正则表达式可视化

Debuggex Demo

调试器演示

I think your second \bis breaking your code also.

我认为你的第二个\b也在破坏你的代码。

Just replace the (S) with value you want to find.

只需将 ( S)替换为您要查找的值。

Not really sure exactly what you're asking to be honest. Or what you are trying to find.

说实话,不太确定您要问什么。或者你想找到什么。

edit:

编辑:

.*?(?:^|\s)(S[^\s$]*).*?

Regular expression visualization

正则表达式可视化

Debuggex Demo

调试器演示

you can prob take out the .*?at the start and the end of the regex put it in there for thoroughness.

您可以.*?在正则表达式的开头和结尾删除它,以便彻底。

replace the Sin front of [^\s$]with the value you want to check. Also, if you want to allow more things in front of the value all you have to do is add an extra |"character"in the first capture group.

用您要检查的值替换S前面的[^\s$]。此外,如果您想在值前面允许更多的东西,您所要做的就是|"character"在第一个捕获组中添加一个额外的东西。

for example a parenthesis

例如括号

.*?(?:^|\s|\()

回答by plalx

Word boundaries are all non-word characters, which includes the .character. You will have to use something else than \b.

字边界都是非字字符,包括.字符。您将不得不使用除\b.

I am sure the regex can be simplified, but you could use something like:

我确信可以简化正则表达式,但您可以使用以下内容:

function containsWord(string, word) {
    return new RegExp('(?:[^.\w]|^|^\W+)' + word + '(?:[^.\w]|\W(?=\W+|$)|$)').test(string);
}

containsWord('test', 'test'); //true
containsWord('.test', 'test'); //true
containsWord('test.something', 'test'); //false
containsWord('test. something', 'test'); //true
containsWord('test.   something', 'test'); //true
containsWord('S.C', 'S'); //false
containsWord('S.C', 'S.C'); //true