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

Regex not to capture if a string contains a word before it

I want to select the word "hazardous" only if it is a separate word and not with "non " or "non-"before it.

eg:

non-hazardous

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

non hazardous

hazardous

non agricultural hazardous

regex 1: ^(?!non[-/s]?)hazardous$
regex 2: ^(?!non-|non\s)hazardous$

I tried the above two regex and it gave correct results for the first 3 sentences, but it’s not selecting hazardous in 4th sentence.
I want to select hazardous in 4th sentence as it doesn’t have "non " or "non-" before it

Reference: Regular Expression – Match pattern that does not contain a string

>Solution :

You can use

r'\b(?<!\bnon[-\s])hazardous\b'

See the regex demo. The pattern matches

  • \b – a word boundary
  • (?<!\bnon[-\s]) – a negative lookbehind that fails the match if there is non- or non and a whitespace immediately to the left of the current location
  • hazardous – a string
  • \b – a word boundary.
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