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?
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(".*\\..*");
 
    
    Maybe you meant:
Pattern.compile("\\*\\.\\*");
If not, and asterisk means 'any character' then
Pattern.compile(".*\\..*");
 
    
    You have to write:
Pattern.compile("\\*\\.\\*");
Because * has a special meaning (zero or more) in a regex. So you have to escape it with a \\.
Another way could be:
Pattern.compile("[*][.][*]");
because * loses its other significance when it appears between [ and ].
If you want to parse a filename of format *.*, this should be enough:
Pattern.compile(".+\\..+");
To match any filename (which may or may not have an extension) you can use
Pattern.compile(".+(\\..+)?");
 
    
    If you mean, you wand to filter out files with a dot "." in its name, use this one:
Pattern.compile("[^\\.]*\\.[^\\.]*")
 
    
    Pattern.compile(".*\\/.*\\..*"); use this pattern.It will match all file names which are containing a dot. Asterisk is a special character. It means that the symbol coming before * can be 0 or more times. So you can't write it without character before.
For example for a file name C:/folder.1/folder.2/file.txt pattern will work so:
.* - C:/folder.1/folder.2 (everything until finds the last / character)
\/ - / character
.* - file (everything until finds the last . character (dot))
\\. - . (dot)
.* - txt (everything after . (actually the file extention))
