简体   繁体   中英

Java Regex Suffix

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM