I\'m writing a simple debugging program that takes as input simple strings that can contain stars to indicate a wildcard match-any
*.wav // matches
Using A Simple Regex
One of this method's benefits is that we can easily add tokens besides * (see Adding Tokens at the bottom).
Search: [^*]+|(\*)
| matches any chars that are not a star\Q + Match + E.*Here is some working code (see the output of the online demo).
Input: audio*2012*.wav
Output: \Qaudio\E.*\Q2012\E.*\Q.wav\E
String subject = "audio*2012*.wav";
Pattern regex = Pattern.compile("[^*]+|(\\*)");
Matcher m = regex.matcher(subject);
StringBuffer b= new StringBuffer();
while (m.find()) {
if(m.group(1) != null) m.appendReplacement(b, ".*");
else m.appendReplacement(b, "\\\\Q" + m.group(0) + "\\\\E");
}
m.appendTail(b);
String replaced = b.toString();
System.out.println(replaced);
Adding Tokens
Suppose we also want to convert the wildcard ?, which stands for a single character, by a dot. We just add a capture group to the regex, and exclude it from the matchall on the left:
Search: [^*?]+|(\*)|(\?)
In the replace function we the add something like:
else if(m.group(2) != null) m.appendReplacement(b, ".");