i wanted to write a file search program where the user can enter the serach pattern(any valid regex) and the file name matching the same will be returned.
e.g MFile123.tx will find UMFile123.txt and AIIMFile123.txs
I tried the following, but it did not work:
import java.util.regex.*;
public class regexTest {
public static void main(String... a){
String file="UMFile123.txt";
//String pattern="*MFile*.tx?"; TRIED with \*MFile*.tx , but no use
String pattern="UMFile*.tx?";
Pattern p=Pattern.compile(pattern);
Matcher m=p.matcher(file);
if(m.matches()){
System.out.println("Hi!it matches!!");
}
}
}
The simplest solution would be to “quote” or “escape” the user entered file name/pattern and prepend & append a
.*?to it. Something like:I would rather not go with the business of manual escaping as mentioned by the other answers here. Tricky to get right IMHO. If you want case-insensitive match, just throw in one of the insensitive regex flags and you should be good.