In Java, how can you determine if a String matches a format string (ie: song%03d.mp3
)?
In other words, how would you implement the following function?
Since you do not know the format in advance, you will have to write a method that converts a format string into a regexp. Not trivial, but possible. Here is a simple example for the 2 testcases you have given:
public static String getRegexpFromFormatString(String format)
{
String toReturn = format;
// escape some special regexp chars
toReturn = toReturn.replaceAll("\\.", "\\\\.");
toReturn = toReturn.replaceAll("\\!", "\\\\!");
if (toReturn.indexOf("%") >= 0)
{
toReturn = toReturn.replaceAll("%s", "[\\\\w]+"); //accepts 0-9 A-Z a-z _
while (toReturn.matches(".*%([0-9]+)[d]{1}.*"))
{
String digitStr = toReturn.replaceFirst(".*%([0-9]+)[d]{1}.*", "$1");
int numDigits = Integer.parseInt(digitStr);
toReturn = toReturn.replaceFirst("(.*)(%[0-9]+[d]{1})(.*)", "$1[0-9]{" + numDigits + "}$3");
}
}
return "^" + toReturn + "$";
}
and some test code:
public static void main(String[] args) throws Exception
{
String formats[] = {"hello %s!", "song%03d.mp3", "song%03d.mp3"};
for (int i=0; i<formats.length; i++)
{
System.out.println("Format in [" + i + "]: " + formats[i]);
System.out.println("Regexp out[" + i + "]: " + getRegexp(formats[i]));
}
String[] words = {"hello world!", "song001.mp3", "potato"};
for (int i=0; i<formats.length; i++)
{
System.out.println("Word [" + i + "]: " + words[i] +
" : matches=" + words[i].matches(getRegexpFromFormatString(formats[i])));
}
}