简体   繁体   中英

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

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

  • At least one character in [az]
  • At least one integer in [0-9], and
  • At least one character in [AZ]

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 ?

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

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)):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM