ddd
ddd

Reputation: 5029

How to exclude word from matching that is optional using regex

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?

Upvotes: 1

Views: 59

Answers (1)

Canyon Turtle
Canyon Turtle

Reputation: 86

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

Upvotes: 2

Related Questions