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

Match words and ignore numbers with Regex

I have a list of words, for example, "at", "in", "on".
I need to match any of those exact words but I’m having some difficulty with one part of it.

Examples:

"I am at work" – should match with "at"

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

"I am attracting honey bees" – should not match

"I am at123" – should match

I currently have something like this, but it’s not doing exactly what i need.

(?i)(\W|^)(at|in|on)(\W|$)

Any assistance is appreciated

>Solution :

It appears that you want to match these words when surrounded by either whitespace, numbers, or the start/end of the string. In that case, we can try using the following pattern:

(?:(?<!\S)|(?<!\D))(?:at|in|on)(?:(?!\S)|(?!\D))

This pattern says to:

  • (?:
    • (?<!\S) lookbehind and assert whitespace or the start of the string precedes
    • | OR
    • (?<!\D) lookbehind and assert that a digit or the start of the string precedes
  • )
  • (?:at|in|on) match at, in, or on
  • (?:
    • (?!\S) lookahead and assert whitespace or the start of the string follows
    • | OR
    • (?!\D) lookahead and assert that a digit or the start of the string precedes
  • )

Demo

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