java - Regex accept max of alpha and alphanumeric with extra % (without limit) -


i dit lot of search in regex posts didn't find solution i'm looking for.

i have fellow regex   ([a-za-z]{6}[a-za-z0-9]{2}([a-za-z0-9]{3})?)?   accept these cases :

  • empty string
  • (6 alpha) + (2 alphanumeric)
  • (6 alpha) + (2 alphanumeric) + (3 alpha)

now, i'm looking modify regex accept optional char % anywhere number of occurence keeping number max of alpha , alphanumeric in current regex.

examples:

  • empty sting -> correct
  • aabb -> wrong (need 6 alpha + 2 alphanumeric when there no %)
  • aabb% -> correct
  • aa33% -> wrong (need 6 alpha before numeric)
  • aa%33 -> correct ( % working wilcard , avoid max number)
  • a%3 -> correct
  • aa%33% -> correct
  • %aa33% -> correct
  • %aa3% -> correct
  • aaaaaa33 -> correct
  • aabbccxx -> correct
  • aabbcc44xxx -> correct
  • aabbcc44xxxe -> wrong (length of alpha not respected)
  • %aabbcc44xxxe -> wrong (length of alpha not respected)
  • %aab%bcc4%4x%xx% -> correct (because % should ignored in length, length of alpha , alphanumeric respected here)

is possible ?

the regex below should close enough.

^(?:(?=.*%)(?![a-z]{1,5}[0-9])(?:%?[a-z]){0,6}(?:(?:%?[a-z0-9]){1,2})?(?:(?:%?[a-z]){1,3})?%?)$|^(?:[a-z]{6}(?:[a-z0-9]{2})(?:[a-z]{3})?)$|^$ 

note how pipes (| = or) separate 3 regexes.
1 %, without % , blanks.

also, character classes use uppercase a-z.
allow lowercases, either let regex ignore case, or replace a-za-z.

you can test here

shorter alternative:

^(?=.*%)(?![a-z]{1,5}[0-9])(?!(?:.*?[0-9]){3})(?:%?[a-z0-9]){1,11}%?$|^(?:[a-z]{6}[a-z0-9]{2}(?:[a-z]{3})?)$|^$ 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -