Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit number of alpha characters in regular expression

Tags:

regex

I've been struggling to figure out how to best do this regular expression.

Here are my requirements:

  • Up to 8 characters
  • Can only be alphanumeric
  • Can only contain up to three alpha characters [a-z] (zero alpha characters are valid to)

Any ideas would be appreciated.

This is what I've got so far, but it only looks for contiguous letter characters:

^(\d|([A-Za-z])(?!([A-Za-z]{3,}))){0,8}$
like image 328
beardedd Avatar asked Jan 02 '26 09:01

beardedd


2 Answers

I'd write it like this:

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

It has two parts:

  • (?=[a-z0-9]{0,8}$)
    • Looksahead and matches up to 8 alphanumeric to the end of the string
  • (?:\d*[a-z]){0,3}\d*$
    • Essentially allowing 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

I do think regex is the best solution for this, but since the string is short, it would be a lot more readable to do this in two steps as follows:

  • It must match [a-z0-9]{0,8}
  • Then, delete all \d
    • The length must now be <= 3
like image 99
polygenelubricants Avatar answered Jan 03 '26 21:01

polygenelubricants


Do you have to do this in exactly one regular expression? It is possible to do that with standard regular expressions, but the regular expression will be rather long and complicated. You can do better with some of the Perl extensions, but depending on what language you're using, they may or may not be supported. The cleanest solution is probably to check whether the string matches:

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

but doesn't match:

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

i.e. it's an alpha string of up to 8 characters (first regular expression), but doesn't contain 4 or more alpha characters (possibly separated by other characters (second regular expression).

like image 30
psmears Avatar answered Jan 03 '26 23:01

psmears



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!