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
  • 277,661
  • 50
  • 283
  • 320
Chetan
  • 1,457
  • 7
  • 29
  • 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
  • 713,503
  • 59
  • 514
  • 593
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
  • 67,942
  • 4
  • 86
  • 123