Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching an input string for occurences of integers and characters using a single regular expression in Python

Tags:

python

regex

I have an input string which is considered valid only if it contains:

  • At least one character in [a-z]
  • At least one integer in [0-9], and
  • At least one character in [A-Z]

There is no constraint on the order of occurrence of any of the above. How can I write a single regular expression that validates my input string ?

like image 456
unni Avatar asked Jan 27 '26 01:01

unni


2 Answers

Try this

^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).*$

See it here online on Regexr

The ^ and $ are anchors which bind the pattern to the start and the end of the string.

The (?=...) are lookahead assertions. they check if the pattern after the = is ahead but they don't match it. So to match something there needs to be a real pattern also. Here it is the .* at the end.
The .* would match the empty string also, but as soon as one of the lookaheads fail, the complete expression will fail.

For those who are concerned about the readability and maintainability, use the re.X modifier to allow pretty and commented regexes:

reg = re.compile(r'''
                ^            # Match the start of the string
                (?=.*[a-z])  # Check if there is a lowercase letter in the string
                (?=.*[A-Z])  # Check if there is a uppercase letter in the string
                (?=.*[0-9])  # Check if there is a digit in the string
                .*           # Match the string
                $            # Match the end of the string
                '''
                , re.X)      # eXtented option whitespace is not part of he pattern for better readability
like image 173
stema Avatar answered Jan 28 '26 14:01

stema


Do you need regular expression?

import string

if any(c in string.uppercase for c in t) and any(c in string.lowercase for c in t) and any(c in string.digits for c in t):

or an improved version of @YuvalAdam's improvement:

if all(any(c in x for c in t) for x in (string.uppercase, string.lowercase, string.digits)):
like image 26
eumiro Avatar answered Jan 28 '26 13:01

eumiro



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!