使用正则表达式在javascript中搜索全字 [英] Whole word search in javascript using regex

查看:60
本文介绍了使用正则表达式在javascript中搜索全字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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



- 编辑 -



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

解决方案

使用捕获组?

 。*?\ b(S)





您可以在开始和结束时取出。*?正则表达式将它放在那里以便彻底。



前面替换 S [^ \ $ $] 包含您要检查的值。
另外,如果你想在值前面允许更多的东西,你只需要在第一个捕获组中添加一个额外的 |character



例如括号

 。*?(?:^ | \ | | \()


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

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.

--Edit--

Thanks to @plalx Clarified the example.

解决方案

Use capture groups?

.*?\b(S)

Debuggex Demo

I think your second \b is breaking your code also.

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

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

edit:

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

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 S in 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.

for example a parenthesis

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

这篇关于使用正则表达式在javascript中搜索全字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆