Jormundir
Jormundir

Reputation: 395

Regular Expression - match whole string or pattern

I'm doing a file search, and I want to exclude files that contain min in them, but I don't want to match parts of words.

so I want to exclude:

a directory named min also a file named jhkjahdf-min.txt

But I don't want to exclude:

a file named mint.txt

Thank you for your help in advanced. Explanations of the regular expression you give would be a lot of extra help.

I'm using PHP's preg_match() function

Upvotes: 2

Views: 2743

Answers (2)

Martin Ender
Martin Ender

Reputation: 44289

There are things called word boundaries (\b). They do not consume a character, but match if you go from a word character (letters, digits, underscores) to a non-word character of vice-versa. So this is a first good approximation:

`\bmin\b`

Now if you want to consider digits and underscores as word boundaries, too, it gets a bit more complicated. Then you need negative lookaheads and lookbehinds, which are not supported by all regex engines:

`(?<![a-zA-Z])min(?![a-zA-Z])`

These will also not be included in the match (if you care about it at all), but just assert that min is neither preceded nor followed by a letter.

Upvotes: 1

OmnipotentEntity
OmnipotentEntity

Reputation: 17131

You'll want to anchor your regex with \b which means "word boundary."

Upvotes: 0

Related Questions