java.util.regex.PatternSyntaxException: Unclosed character class near index 28

1.8k Views Asked by At
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
2

There are 2 best solutions below

0
On

The expression is invalid.

The closing bracket will be escape because you used '\\]' in the expression.

solution 1: You can use like ' \\\\] '.

or

solution 2: You can handle the exception to get user friendly message like below,

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);
    }
}
0
On

The expression [^\\] causes the regular expression compiler to crash (@KevinEsche noted that in a comment) because the closing bracket ] was escaped. 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: [^\\\\]