Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to exclude certain word when it is optional?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading