0
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
Martin Evans
  • 45,791
  • 17
  • 81
  • 97
  • 2
    you need to escape the `(` as `\\(` – SomeJavaGuy Oct 12 '15 at 05:59
  • 2
    In addtion `[^\\]` doesn´t compile because you escape the `]` and the char class is never closed. – SomeJavaGuy Oct 12 '15 at 06:07
  • @KevinEsche Actually, according to [regex101](https://regex101.com/r/iP4zT5/1), you don't _need_ to escape a paranthesis `()` inside a character group. The exception also doesn't refer to that paranthesis but rather the second issue you noted (the 29th character is the closing paranthesis `)` right before the end of the regex). – mezzodrinker Oct 12 '15 at 06:21

2 Answers2

0

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

mezzodrinker
  • 998
  • 10
  • 28
0

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);
    }
}
TT.
  • 15,774
  • 6
  • 47
  • 88