简体   繁体   中英

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. 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: [^\\\\\\\\]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM