Kesong Xie
Kesong Xie

Reputation: 1396

How do you use regular expressions to check if a String in Java ends with at least one digit?

I try to use the regex to check the username should start with letters and ends with at least one digit, but the following code only allows me to end with 1 digit, and I'm not sure about whether I used the * correctly, I think "[regex]*" means match at least one times [regex]

if( username.matches("^[a-zA-z]*\\d*$") ){
System.out.println("The username is valid");

}
else{
System.out.println("The username is invalid");

}

Upvotes: 1

Views: 66

Answers (1)

Dan Harms
Dan Harms

Reputation: 4840

You were close:

^[a-zA-z]+[\d]+$

^[a-zA-z]+ make sure there is at least one character at the beginning of the string.

[\d]+$ make sure there is at least one digit at the end.

Upvotes: 2

Related Questions