Ofri Rips
Ofri Rips

Reputation: 153

regex negative lookahead - exclude the exact word

I need to modify an identifier, and it has a certain first letter, and zero or more continue letters, and I want to exclude some reserved words. For the example I'm using the same first and continue letters:

(?!(abstract|alignof|as|impl|in|let|mut))[a-z][a-z]*

so abstract|alignof|as|impl|in|let|mut are the words I don't want to match, the thing is, with this regex I cant match the word "letter" because of "let". it only matches "etter"

I also tried this:

(?!(abstract|alignof|as|impl|in|let|mut))\b[a-z][a-z]*\b

but it doesn't seem to work. How can I exclude the exact word?

Thanks

Upvotes: 2

Views: 3928

Answers (1)

nhahtdh
nhahtdh

Reputation: 56809

You need to add word boundary check for the words in the look-ahead also:

(?!\b(abstract|alignof|as|impl|in|let|mut)\b)\b[a-z][a-z]*\b

Technically, the first \b is redundant, since \b is checked outside the look-ahead. Since word boundary and look-ahead assertions are zero-length, we can swap them around:

\b(?!(abstract|alignof|as|impl|in|let|mut)\b)[a-z][a-z]*\b

Upvotes: 1

Related Questions