[英]java.util.regex.PatternSyntaxException: Unclosed character class near index 28
public class samppatmatch {
private boolean validatingpswwithpattern(String password){
String math="[a-zA-z0-9]+[(]+(?:[^\\]+|\\.)*";
Pattern pswNamePtrn =Pattern.compile(math);
boolean flag=false;
Matcher mtch = pswNamePtrn.matcher(password);
if(mtch.matches()){
flag= true;
}
return flag;
}
public static void main(String args[]){
samppatmatch obj=new samppatmatch();
boolean b=obj.validatingpswwithpattern("");
System.out.println(b);
}
}
I am getting this type of exception for above code: 我收到上述代码的这种类型的异常:
java.util.regex.PatternSyntaxException: Unclosed character class near index 28
The expression [^\\\\]
causes the regular expression compiler to crash (@KevinEsche noted that in a comment) because the closing bracket ]
was escaped. 表达式
[^\\\\]
导致正则表达式编译器崩溃(@KevinEsche在注释中指出),因为转义了右括号[ ]
。 If you wanted to create a character class containing a \\
, you need to escape it as well so that the character class would look like this in a Java string: [^\\\\\\\\]
如果要创建包含
\\
的字符类,则还需要对其进行转义,以使字符类在Java字符串中看起来像这样: [^\\\\\\\\]
The expression is invalid. 表达式无效。
The closing bracket will be escape because you used '\\\\]'
in the expression. 由于在表达式中使用了
'\\\\]'
,因此右括号将被转义。
solution 1: You can use like ' \\\\\\\\] '
. 解决方案1:您可以使用
' \\\\\\\\] '
。
or 要么
solution 2: You can handle the exception to get user friendly message like below, 解决方案2:您可以处理异常以获取如下所示的用户友好消息,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
public class samppatmatch {
private boolean validatingpswwithpattern(String password) {
boolean flag = false;
try {
String math = "[a-zA-z0-9]+[(]+(?:[^\\]+|\\.)*";
Pattern pswNamePtrn = Pattern.compile(math);
Matcher mtch = pswNamePtrn.matcher(password);
if (mtch.matches()) {
flag = true;
}
} catch (PatternSyntaxException pe) {
System.out.println("Invalid Expression");
}
return flag;
}
public static void main(String args[]) {
samppatmatch obj = new samppatmatch();
boolean b = obj.validatingpswwithpattern("Admin@123");
System.out.println(b);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.