-1

I am trying to find a regex that matches a combination of letters and digits, each type has to occur at least once. I found out that this can be achieved using:

([a-z]+\d+|\d+[a-z]+)[a-z\d]*

However, I want the whole string to be at least 3 chars and at most 5 chars long. Is there a way to do this?

Thanks in advance!

MyLion
  • 59
  • 5
  • Can you demonstrate *any* evidence of trying to solve this yourself? – Scott Hunter Nov 10 '19 at 20:37
  • [Specifying number of matches](https://stackoverflow.com/questions/17032914/what-does-comma-separated-numbers-in-curly-brace-at-the-end-of-regex-means) – DarrylG Nov 10 '19 at 20:40

1 Answers1

4

Guess 1

My guess is that, maybe

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

or

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

might be desired, if two consecutive letters or digits wouldn't be allowed.

RegEx Demo 1


Guess 2

If we want to at least have a letter and a digit:

^(?=.*[a-z])(?=.*[0-9])[a-z0-9]{3,5}$

might be an option.

RegEx Demo 2


Guess 3

If any 3 to 5 times letters or digits are allowed:

^[a-z0-9]{3,5}$

might just work fine.

RegEx Demo 3

Test

import re

string = '''
aaa
aaa1
aaab1
a1
a1b2
a1b2c3
a1b2c3d4
'''

expression = r'^(?=.*[a-z])(?=.*[0-9])[a-z0-9]{3,5}$'

print(re.findall(expression, string, re.M))

Output

['aaa1', 'aaab1', 'a1b2']

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Emma
  • 26,487
  • 10
  • 35
  • 65
  • 1
    Thanks a lot for your answer! It appears that this regex only matches strings with alternating digits/letters, i.e. "a1b1" but I would like to also be able to match strings like "abc4" or "a45b6" etc.. Thanks also for the links, looks very helpful – MyLion Nov 10 '19 at 20:50
  • 1
    Yes, I was just going to say that. The regex you provided seems to still match strings which only consist of digits/letters though but again, thanks for the help (or maybe I'm not using the regex tester correctly) – MyLion Nov 10 '19 at 20:59
  • 1
    Yeahh!! perfect! Thank you! – MyLion Nov 10 '19 at 21:03