Fjott
Fjott

Reputation: 1137

Regex match exact words

I want my regex to match ?ver and ?v, but not ?version

This is what I have so far: $parts = preg_split( "(\b\?ver\b|\b\?v\b)", $src );

I think the trouble might be how I escape the ?.

Upvotes: 2

Views: 14484

Answers (3)

Hassan Amin
Hassan Amin

Reputation: 142

Building upon above answers, to match a word without being a part of another you can try \b(WORD_HERE)\b which in your case is \b(\?ver)\b this will allow ver and prevent version average

Upvotes: 1

Tom Wyllie
Tom Wyllie

Reputation: 2085

Try the following regex pattern;

(\?v(?:\b|(?:er(?!sion))))

Demo

This will allow ?ver and ?v, but will use a negative look-ahead to prevent matching if ?ver is followed by sion, as in your case ?version.

Upvotes: 5

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627600

Your pattern tries to match a ? that is preceded with a word char, and since there is none, you do not have a match.

Use the following pattern:

'/\?v(?:er)?\b/'

See the regex demo

Pattern details:

  • \? - a literal ? char
  • v(?:er)? - v or ver
  • \b - a word boundary (i.e. there must be a non-word char (not a digit, letter or _) or end of string after v or ver).

Note you do not need the first (initial) word boundary as it is already there, between a ? (a non-word char) and v (a word char). You would need a word boundary there if the ? were optional.

Upvotes: 7

Related Questions