javascript - Regex ignore match if substring of a specific word - Stack Overflow

I'm trying to match a text string in javascript as long as it isn't a substring of a predefin

I'm trying to match a text string in javascript as long as it isn't a substring of a predefined word.

E.g. 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. If the user were to search for ue, only value and clue should be matched.

I tried doing a negative look ahead like this;

((?!blue)lu)

Didn't work though and I'm not sure what else to do.

I'm trying to match a text string in javascript as long as it isn't a substring of a predefined word.

E.g. 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. If the user were to search for ue, only value and clue should be matched.

I tried doing a negative look ahead like this;

((?!blue)lu)

Didn't work though and I'm not sure what else to do.

Share Improve this question edited May 29, 2017 at 12:53 revo 48.8k15 gold badges83 silver badges122 bronze badges asked May 29, 2017 at 12:29 user3163192user3163192 1112 silver badges9 bronze badges 9
  • So if I understand correct, you want clue to be in result, but not blue. Am I right? – Rajesh Commented May 29, 2017 at 12:32
  • 2 You have to use word boundaries : \blu\b – revo Commented May 29, 2017 at 12:33
  • Request for clarification, I don't want the word blue... then why only word blue? – revo Commented May 29, 2017 at 12:38
  • @revo this was just a simplified example of what I want to do. In any case, I want to know how to do, I don't have anything against the word blue ;) – user3163192 Commented May 29, 2017 at 12:41
  • 2 See @anubhava's answer. It seems to be a solution to your problem. – revo Commented May 29, 2017 at 12:48
 |  Show 4 more ments

1 Answer 1

Reset to default 7

You need to place \w* to match 0 or more word characters between negative lookahead and your search string.

With lu as search string:

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

With ue as search string:

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

RegEx Demo

Actual Javascript code can be this:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745432882a4627473.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信