1

I have written below regular expression in java for checking the validity of a string, but unfortunately it doesn't work.

^[a-zA-Z][a-zA-Z0-9_]

Rule:

string can be alpha numeric and _ is the only allowed special chars

string can start with only alphabets a-z or A-Z

below java code returns false even though all conditions are met.

"a1b".matches("^[a-zA-Z][a-zA-Z0-9_]")
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Chetan
  • 1,507
  • 7
  • 30
  • 43

2 Answers2

3

You need to use quantifier * to make your regex match 0 or more times after first alphabet:

"a1b".matches("[a-zA-Z][a-zA-Z0-9_]*");

Or else use:

"a1b".matches("[a-zA-Z]\\w*");

PS: No need to use anchors ^ and $ in String#matches since that is already implied.

anubhava
  • 761,203
  • 64
  • 569
  • 643
3

Remove the beginning of line ^ anchor and place a quantifier after your last character class []

System.out.println("a1b".matches("[a-zA-Z][a-zA-Z0-9_]*")); // true

You could simply use..

System.out.println("a1b".matches("(?i)[a-z][a-z0-9_]*")); // true
hwnd
  • 69,796
  • 4
  • 95
  • 132