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 regex match words with/without hyphen

I’m having a lot of difficulties matching strings in JavaScript using regex. Problem is when I match strings like "assistant-attorney" with "attorney" it returns true. I cannot ignore/forbid hyphens, as I also want to be able to match "assistant-attorney" with "assistant-attorney" and also get true. Can’t figure out if I should use word boundaries, or check if string does not start with white space or hyphen.

What I have so far is this:

([^-])(attorney)

Here’s a test:
https://www.regextester.com/?fam=121381

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

Hope anyone can help, thanks in advance.

>Solution :

I think you need to use word boundaries and enhance them with additional requirements:

(?<=^|[^-])\battorney\b(?=[^-]|$)
  • (?<=^|[^-]) – assert that behind me is the start of a line or is not a hyphen
  • \b – word boundary
  • attorney – the search term
  • \b – word boundary
  • (?=[^-]|$) – assert that in front of me is not a hyphen or is the end of a line

attorney – https://regex101.com/r/HCRKWi/1

assistant-attorney – https://regex101.com/r/2tvU1n/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