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)*top\sof\s(existing\s)?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?
CodePudding user response:
You can exclude a certain word like this:
(\w \s(?<!proposed\s))?top\sof\s(existing\s)?hole
There are a couple of things going on in this solution:
\w \s
matches a word and 1 whitespace character,The negative lookbehind
(?<!proposed\s)
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