【发布时间】:2014-05-13 20:35:09
【问题描述】:
我正在尝试创建一个 Java 正则表达式,如果字符串末尾有奇数个反斜杠(),它将返回 true,如果偶数则返回 false。
这是我的正则表达式
String regex = "^.*[^\\](\\\\)*\\$";
Pattern pattern = Pattern.compile(regex);
当我编译代码时出现以下异常
线程“main”java.util.regex.PatternSyntaxException 中的异常:索引 15 附近的未封闭字符类 ^.([^])(\)\$
如果我使用 M 模式代替反斜杠编译并且工作正常
String regex = "^.*" + "[^M]" + "(MM)*M$";
我知道这是一种逃避问题,但我无法弄清楚。以下是整个方法
private static void testSpecificRegex() {
String a = "india\\";
String b = "india\\\\";
String c = "india\\\\\\";
String d = "india\\\\\\\\";
/* String a = "indiaM";
String b = "indiaMM";
String c = "indiaMMM";
String d = "indiaMMMM";*/
String regex = "^.*[^\\](\\\\)*\\$";
//String regex = "^.*" + "[^M]" + "(MM)*M$";
System.err.println(regex);
Pattern pattern = Pattern.compile(regex); // why i need to compile
Matcher matcher = pattern.matcher(a);
System.err.println(matcher.matches());
matcher = pattern.matcher(b);
System.err.println(matcher.matches());
matcher = pattern.matcher(c);
System.err.println(matcher.matches());
matcher = pattern.matcher(d);
System.err.println(matcher.matches());
}
【问题讨论】: