Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match filename containing a word, regardless of case

Tags:

regex

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

like image 511
tzippy Avatar asked Dec 19 '25 17:12

tzippy


2 Answers

Like @Sebastian P mentioned:

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

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

like image 127
Brad Christie Avatar answered Dec 21 '25 21:12

Brad Christie


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:

  • Java 6 documentation on the Pattern class
like image 35
Sebastian Paaske Tørholm Avatar answered Dec 21 '25 20:12

Sebastian Paaske Tørholm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!