Search code examples
javaregexpatternsyntaxexception

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?


Solution

  • 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.