Following String causes PatternSyntaxException:
Pattern.compile("*\\.*");
I want to create a pattern so that I can filter all files with the name in the following form: "*.*"
How can I do that?
To match all strings with a . in the name, you do:
Pattern.compile(".*[.].*");
To break it down:
.* match any number of arbitrary character[.] match a dot. (yes, \\. works too).* match any number of arbitrary characterDemo:
Pattern p = Pattern.compile(".*[.].*");
System.out.println(p.matcher("hello.txt").matches()); // true
System.out.println(p.matcher("hellotxt").matches()); // false
Note that the string with just one dot, "." matches as well. To ensure that you have some characters in front and after the dot, you could change the * to +: .+[.].+.
The reason you get PatternSyntaxException:
The * operator is to be interpreted as "the previous character repeated zero or more times". Since you started your expression with * there was no character to repeat, thus an exception was thrown.
The * character has a different meaning in regular expressions than when used on the command line as a file wildcard. More information about the Java Pattern regular expression syntax can be found here: http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
This will find the text you are looking to match:
Pattern.compile(".*\\..*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With