luffe
luffe

Reputation: 1665

Regex non-greedy exact match

I am using a regex to find the group of strings than matches my list of prefixes exactly.

With prefixes A, B, BB

I can match the three groups (Aone Atwo, BBone BBtwo, Bone Btwo)

Aone
Atwo
BBone
BBtwo
Bone
Btwo

using the regex ^prefix[^prefix]

But this breaks if I have the strings

incd
incm    
named   
namem

where my prefixs are inc, name

The namem is not captured. Any ideas of what I could do here?

Upvotes: 1

Views: 154

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

When you "negate" a single char with a negated character class, you require a char other than the one(s) defined in the class. More important thing is that you can only "negate" only a single char this way, not a sequence of characters.

A more universal approach is to use a negative lookahead, (?!...).

^(?:inc|name)(?!(?:inc|name))

See the regex demo

  • ^ - matches the string start
  • (?:inc|name) - matches either inc or name
  • (?!(?:inc|name)) - asserts that there is no inc or name literal character sequences right after inc or name

Upvotes: 1

Related Questions