Limit the number of alpha characters in a regular expression

I am trying to figure out how best to do this regex.

Here are my requirements:

  • Up to 8 characters
  • Can only be alphanumeric
  • Can only contain up to three alpha characters [az] (valid zero alpha characters)

Any ideas would be appreciated.

This is what I got so far, but it only searches for adjacent letters:

^(\d|([A-Za-z])(?!([A-Za-z]{3,}))){0,8}$
+3
source share
4 answers

I would write it like this:

^(?=[a-z0-9]{0,8}$)(?:\d*[a-z]){0,3}\d*$

It consists of two parts:

  • (?=[a-z0-9]{0,8}$)
    • Looksahead and matches 8 alphanumeric characters at the end of a line
  • (?:\d*[a-z]){0,3}\d*$
    • Essentially allows injection of up to 3 [a-z]among\d*

Rubular

On rubular.com

12345678    // matches
123456789
@(#*@$
12345       // matches
abc12345
abcd1234
12a34b5c    // matches
12ab34cd
123a456     // matches

Alternatives

, regex - , , :

  • [a-z0-9]{0,8}
  • \d
    • <= 3
+7

? , . Perl, , , . - , :

^[A-Za-z0-9]{0,8}$

:

([A-Za-z].*){4}

. - 8 ( ), 4 - (, ( ).

+2
/^(?!(?:\d*[a-z]){4})[a-z0-9]{0,8}$/i

:

  • [a-z0-9]{0,8} 8 - .
  • Lookahead , .
  • (?:\d*[a-z]) 1 . {4} 4. , , 4 (.. ≤3).

. , , , , , ? - , .

if len(theText) <= 8 and theText.isalnum():
   if sum(1 for c in theText if c.isalpha()) <= 3:
      # valid
+1

- :

  • /^[a-z0-9]{0,8}$/i - 8 -
  • ,
  • , 3 .

, - :

/^(?=\d*(?:[a-z]?\d*){0,3}$)[a-z0-9]{0,8}$/i

Which searches for an alphanumeric string between lengths 0 and 8 ( ^[a-z0-9]{0,8}$), but first uses lookahead ( (?=\d*(?:[a-z]?\d*){0,3}$)) to make sure that the string has at most 3 alphanumeric characters.

0
source

Source: https://habr.com/ru/post/1749224/


All Articles