0

My test method is here and all the other inputs are fine but the problem is can't test on the string containing \ backslash character,

public static void main(String[] args) {
    String reg2 = "^[a-zA-Z0-9@\\#$%&*()_+\\]\\[';:?.,!^-]{8,}$";

    System.out.println("".matches(reg2));
    System.out.println("Pass".matches(reg2));
    System.out.println("P@ssw0r\\".matches(reg2)); //not work
    System.out.println("P@ssw0r$".matches(reg2));       
    System.out.println("P@ssw0r(".matches(reg2));
    System.out.println("P@ssw0r)".matches(reg2));
    System.out.println("P@ssw0r_".matches(reg2));
    System.out.println("P@ssw0r+".matches(reg2));
    System.out.println("P@ssw0r'".matches(reg2));
    System.out.println("P@ssw0r;".matches(reg2));
    System.out.println("P@ssw0r:".matches(reg2));
    System.out.println("P@ssw0r?".matches(reg2));
    System.out.println("P@ssw0r.".matches(reg2));
    System.out.println("P@ssw0r.][".matches(reg2));
}

Please suggest my regular expression to work on the string with \ character, and guide me if my approach is wrong.

Wundwin Born
  • 3,279
  • 17
  • 35
  • Refer this link solution is already there http://stackoverflow.com/questions/3802192/regexp-java-for-password-validation – Ashok_Pradhan May 29 '14 at 10:27
  • @Ashok_Pradhan Thanks for your help. But my requirement is any number of any alphanumeric characters and special characters. – Wundwin Born May 29 '14 at 10:31

1 Answers1

1

Escapse \ character twice (one for java and one for regex)

String reg2 = "^[a-zA-Z0-9@\\\\#$%&*()_+\\]\\[';:?.,!^-]{8,}$";
Prince John Wesley
  • 58,850
  • 11
  • 80
  • 91