最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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*");
发布评论

评论列表(0)

  1. 暂无评论