简体   繁体   中英

How to exclude a string from my RegEx in Javascript?

please excuse my title. Didn't know a better one. My problem. I have to find words. This words can have square brackets / parentheses around them or be in quotation marks. To find all words I use:

new RegEx('\\b' + arrWord + '\\b', 'g');

Now the problem. Some words have for example ["DN"]word or...ignore">,... in front of them. This words I don't want to find. I read something about RegEx exclude a string, but I can't get it to work. Does someone have an idea or can help? Or is it not possible to do something like that with RegEx in Javascript?

You can use something like this to do what's called in REGEX "negative lookahead":

\bword\b(?!...ignore)

This was kind of tricky because ["DN"] matches with "surrounded by quotations", so the final regex is a bit long. Here you have it with some examples, and the regex itself is:

(?<!\[\"DN\"\])(?<!\.\.\.ignore)(\[\w+\]|\(\w+\)|(\"\w+\")(?=(?<!\"DN\")))

Here you can see how it is composed:

  • (?<!\[\"DN\"\]) asserts that the following string does not match ["DN"] .
  • (?<.\.\.\.ignore) asserts that the following string does not match ...ignore .
  • (\[\w+\]|\(\w+\)|(\"\w+\")(?=(?<!\"DN\"))) is composed by 3 OR conditions:
    • \[\w+\] matches if word is surrounded by brackets.
    • \(\w+\) matches if word is surrounded by parenthesis.
    • (\"\w+\")(?=(?<!\"DN\")) matches if word surrounded by quotations and is not "DN" .

I hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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