Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PatternSyntaxException

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?

like image 772
Caner Avatar asked Oct 09 '22 18:10

Caner


2 Answers

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 character

Demo:

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.

like image 181
aioobe Avatar answered Oct 11 '22 07:10

aioobe


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(".*\\..*");
like image 34
Nick Garvey Avatar answered Oct 11 '22 06:10

Nick Garvey