Skip to content
Advertisement

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

Hope anyone can help, thanks in advance.

Advertisement

Answer

I think a simple Negative Lookbehind group could do the trick

(?<!-)attorney

Negative Lookbehind (?<!-) Assert that the Regex below does not match

UPDATE

As @MonkeyZeus said, the first version failed on attorneys and fakewordwithattorneyinit

The new regexp is using negative lookbehind and negative lookahead look like this :

b(?<!-)attorney(?!-)b if you want to match in all string enter image description here

^b(?<!-)attorney(?!-)b if you want to match “line begins with term”

https://regex101.com/r/FToha6/1

Advertisement