tzippy
tzippy

Reputation: 6638

Regex to match filename containing a word, regardless of case

I need a regex that matches any filename of the type .png containing the word icon in all its cases. So it should match

icon.png
myicon.png
thisIcon.PnG
aniCon_this.png
ANYICON.PNG
[email protected]

Any help appreciated!! Thanks! PS: I'm in java

Upvotes: 2

Views: 27331

Answers (3)

tchrist
tchrist

Reputation: 80423

The pattern you need is something like this:

(?xsiu) \A .* icon .* \. png \z

Upvotes: 0

If you only need to verify filenames, this should do the trick:

Pattern regex = Pattern.compile("^.*icon.*\\.png$", Pattern.CASE_INSENSITIVE);

If you get paths also, and want to extract the filename, use this:

Pattern regex = Pattern.compile("(?<=^|[\\\\/])([^\\\\/]*icon[^\\\\/]*\\.png)$", Pattern.CASE_INSENSITIVE);

To explain this one: I use negated character classes for \ and / to ensure that everything is part of the filename, and then I ensure that we go until the start of the filename with a lookbehind.

See also:

Upvotes: 4

Brad Christie
Brad Christie

Reputation: 101614

Like @Sebastian P mentioned:

/^.*icon.*\.png$/i

Except I'm adding the i flag to the end to mark it as case-insensitive.

Upvotes: 8

Related Questions