pattern Recognizer in java
I'm writing a file renamer program in java. The issue is when giving input pattern.
Wh开发者_开发技巧en the input is complex like (][) in that case, I'm getting errors by java.util.regex.Pattern class..
The major issue of writing this code is that the input pattern and replacement pattern are user input. How can I handle such characters during processing ???
This is an example of how one can escape the special RegExp characters in the Java source code. I believe that you will have to escape the special characters manually if the pattern is being entered by a user.
package edu.mew.test.regexp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegExpPatternTester {
public static void main(String[] args) {
String s1 = "filename()[].txt";
Pattern p = Pattern.compile(".*\\(\\)\\[\\].*");
Matcher m1 = p.matcher(s1);
System.out.println(m1.matches());
String s2 = "filename.txt";
Matcher m2 = p.matcher(s2);
System.out.println(m2.matches());
}
}
You can escape special characters in a regular expression using Pattern.quote.
They are reserved characters in regex you need to escape them with two backslashes
//]
OOPS too much Microsoft influence I meant
backslashes \\]
http://download.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html
精彩评论