PermaLink Converting Filename Wildcard to Standard RegEx09/27/2005 03:50 PM
In case you ever need to allow users to specify a wildcard listing for files, you can use this to convert a DOS/Windows/Unix wildcard style string into a regular regex for use with Java's built-in regular expression classes.  It took a while for me to find in Google, so I'm putting this in my blog in case anyone else needs it If you want to support case-sensitive matching, remember to remove the toLowerCase() call on the return statement:

/**
* Converts a windows wildcard pattern to a regex pattern
*
* @param wildcard - Wildcard pattern containing * and ?
*
* @return - a regex pattern that is equivalent to the windows wildcard pattern
*/
private static String wildcardToRegex(String wildcard)
{
if (wildcard == null) return null;

StringBuffer buffer = new StringBuffer();

char [] chars = wildcard.toCharArray();
for (int i = 0; i < chars.length; ++i) {
  if (chars[i] == '*')
    buffer.append(".*");
  else if (chars[i] == '?')
    buffer.append(".");
  else if ("+()^$.{}[]|\\".indexOf(chars[i]) != -1)
    buffer.append('\\').append(chars[i]); // prefix all metacharacters with backslash
  else
    buffer.append(chars[i]);
}

return buffer.toString().toLowerCase();
}

Comments :v

1. Greg12/30/2009 16:06:16


Thanks for the post, and Ray for your comment! This is just what I needed. In my case, I needed to work with multiple wildcard patterns, such as *.zip AND *.xml at the same time, as well as ignore anything with a .include extension, so I ended up sticking a (?!.*\.ignore$) at the start of the regex and called your code in a loop, resulting in the following, which I've posted in the hopes that someone would find it helpful:

^(?!.*\.ignore$)(.*\.xml)|(.*\.zip)$




2. Ray10/04/2008 19:18:03


One small improvement, make your return string start with ^ and end with $

At the moment if you supplied ello*.* it would match yellow.txt which it shouldn't!




Start Pages
RSS News Feed RSS Comments Feed CoComment Integrated
The BlogRoll
Calendar
December 2024
Su
Mo
Tu
We
Th
Fr
Sa
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Search
Contact Me
About Ken
Full-stack developer (consultant) working with .Net, Java, Android, Javascript (jQuery, Meteor.js, AngularJS), Lotus Domino