How to exclude word from matching that is optional using regex
Question:
I want to be able to match the following:
top of pole
top of existing pole
existing top of pole
but not
proposed top of pole
I tried to use ((!=proposed)s)*topsofs(existings)?pole
with look back, but it doesn’t quite work, still matching proposed
top of pole.
How to exclude certain word when it is optional?
Answers:
You can exclude a certain word like this:
(w+s(?<!proposeds))?topsofs(existings)?hole
There are a couple of things going on in this solution:
-
w+s
matches a word and 1 whitespace character,
-
The negative lookbehind (?<!proposeds)
gurantees that, once the regex is at this position after the word and space, looking backwards we do not match "proposed ".
-
The (...)?
makes the (word, space, and no "proposed ") match optional.
For a more detailed walkthrough: https://regex101.com/r/LLs2zA/1
I want to be able to match the following:
top of pole
top of existing pole
existing top of pole
but not
proposed top of pole
I tried to use ((!=proposed)s)*topsofs(existings)?pole
with look back, but it doesn’t quite work, still matching proposed
top of pole.
How to exclude certain word when it is optional?
You can exclude a certain word like this:
(w+s(?<!proposeds))?topsofs(existings)?hole
There are a couple of things going on in this solution:
-
w+s
matches a word and 1 whitespace character, -
The negative lookbehind
(?<!proposeds)
gurantees that, once the regex is at this position after the word and space, looking backwards we do not match "proposed ". -
The
(...)?
makes the (word, space, and no "proposed ") match optional.
For a more detailed walkthrough: https://regex101.com/r/LLs2zA/1