简体   繁体   English

如果特定单词的子字符串,则正则表达式忽略匹配

[英]Regex ignore match if substring of a specific word

I'm trying to match a text string in javascript as long as it isn't a substring of a predefined word. 我正在尝试匹配JavaScript中的文本字符串,只要它不是预定义单词的子字符串即可。

Eg let's say we have these words in the file and even if there's a match, I don't want the word blue to show up in the search; 例如,假设我们在文件中包含这些单词,即使存在匹配项,我也不希望在搜索中显示蓝色单词;

value
lunar
blue
clue

So if the user searches for lu , all the words other than blue should show up. 因此,如果用户搜索lu ,则应该显示除blue以外的所有单词。 If the user were to search for ue , only value and clue should be matched. 如果用户要搜索ue ,则仅值和线索应该匹配。

I tried doing a negative look ahead like this; 我尝试过这样的消极眼光:

((?!blue)lu)

Didn't work though and I'm not sure what else to do. 虽然没有用,但我不确定该怎么办。

You need to place \\w* to match 0 or more word characters between negative lookahead and your search string. 您需要放置\\w*以在负前瞻和搜索字符串之间匹配0个或多个单词字符。

With lu as search string: 使用lu作为搜索字符串:

/\b(?!blue)\w*lu\w*/

With ue as search string: 使用ue作为搜索字符串:

/\b(?!blue)\w*ue\w*/

RegEx Demo 正则演示

Actual Javascript code can be this: 实际的Javascript代码可以是这样的:

var kw = "lu"; or "ue"
var re = new RegExp("\\b(?!blue)\\w*" + kw + "\\w*");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM