简体   繁体   中英

how to write this regex with fixed length and many elements

the string start with character following with number(both the character and number can be empty), but the total length should be no more than 8.

my solution is

([a-zA-Z]*[0-9]*){0,8}

seems like total length 8 cannot work, so how to do that

To check length of string with regex you can use look ahead mechanism and add (?=^.{0,8}$) at start of regex. ^ is anchor representing beginning of data, $ represents end.

But in your case I would probably use something like

someString.matches("^(|[a-zA-Z]\\d{0,7})$")

It will accept

  • empty String,
  • String containing only one letter at start and up to 7 digits.

I think this will work ([a-zA-Z]|[0-9]){0,8}

If not try use this tool gskinner Or www.rubular.com

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