0

I already Read the Post on Regular Expression in Java for validating username

I tried to do it myself. with JAVA 1.7

String value="12345_-6zA";
Boolean result= value.matches("[a-zA-Z0-9_-]");
System.out.println(result);

I also Tried

String value="12345a";
Boolean result= value.matches("[a-zA-Z0-9_-]")
System.out.println(result);

But both gives me result "False" , the String value only contained the char the regex said. I cant figure out why it returned false.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
runcode
  • 3,533
  • 9
  • 35
  • 52

1 Answers1

4

You are missing quantifier + which would make sure to match 1 or of those characters in your character class:

Use this:

boolean result = value.matches("[a-zA-Z0-9_-]+");

Or even better:

boolean result = value.matches("[\\w-]+");

Since \w is equivalent of [a-zA-Z0-9_]

anubhava
  • 761,203
  • 64
  • 569
  • 643