1

I am currently working with java regexes attempting to match a username with the following conditions:

  1. Must start with letter (upper or lower case)
  2. Must be no more than 8 chars in length
  3. May have digits, but they must be at the end (so sjh23 would match but not sj23h)

I know to start with ^[A-Za-z] and the length can be managed with {0,7} but I don't know how to make it so any digits would be a suffix.

Thanks for any help.

4

1 回答 1

4

To check length of string with regex you can use look ahead mechanism and add (?=^.{1,8}$) at start of regex.

So your regex can look like

(?=^.{1,8}$)[A-Za-z]+\\d*

Also you can do it with length() method like

if(yourString.matches("[A-Za-z]+\\d*")  &&  yourString.length()<=8){//...
//you dont need to check if yourString.length()>=1 since [A-Za-z]+ makes string
//to contain at least one character
于 2013-03-29T23:32:24.083 回答