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_]")
0

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.