需要特定的 Javascript 匹配正则表达式
我目前有以下内容:
var sText = 'I like stackoverflow';
if ( $(this).text().match( eval("/" + sText + "/ig") ) ) {
如您所见,这与整个字符串匹配。
我需要匹配单独包含所有单词的不区分大小写的文本。所以它会寻找“I”、“like”和“stackoverflow”。它必须包含全部 3 个词。
非常感谢您的帮助。
I currently have the following:
var sText = 'I like stackoverflow';
if ( $(this).text().match( eval("/" + sText + "/ig") ) ) {
As you can see, this matches the entire string.
I need to match case insensitive text that contains all the words individually. So it will look for "I", "like" and "stackoverflow". It must have all 3 words.
Much appreciate the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您确实需要通过匹配来执行此操作,则可以使用多个正向先行模式。例如,要以任意顺序匹配
a
、b
和c
:If you really need to do this with a match, you can use multiple positive lookahead patterns. For example, to match
a
,b
, andc
, in any order:当
.indexOf
可以完成这项工作时,为什么还要使用正则表达式呢?(请注意,在这种情况下,“i”搜索被浪费了,因为它包含在“like”中,但我假设您的实际代码正在搜索更普通的文本。)
可能的相关问题:JavaScript:不区分大小写的搜索
Why use regular expressions when
.indexOf
will do the job?(Mind you, in this case the "i" search is wasted since it's contained in "like", but I assume your actual code is searching for more ordinary text.)
Possible related question: JavaScript: case-insensitive search
你可以先分割然后循环——
如果你要比较很多单词,你需要记住效率。
You could just split then loop -
You'd need to keep efficiency in mind if you were comparing lots of words though.
我认为这就是您要寻找的 - 关键是单词边界。
JSFiddle 示例。
I think this is what you're looking for - the key is the word boundaries.
JSFiddle example.