I try to put this steps in one, but it doesnt work
w = re.sub(\'[0-9]\', r\'9\', w)
w = re.sub(\'[A-Z]\', r\'X\', w)
w = re.sub(\'[a-z]\', r\'x\', w)
You may use a callback method as a replacement argument like this:
import re
rx = r'([0-9]+)|([A-Z]+)|[a-z]+'
w = "XXxxxx999"
def repl(m):
if m.group(1): # if ([0-9]) matched
return '9' # replace with 9
elif m.group(2): # if ([A-Z]) matched
return 'X' # replace with X
else: # if ([a-z]) matched
return 'x' # replace with x
print(re.sub(rx, repl, w)) # => Xx9
See the Python demo.
The regex matches:
([0-9]+)
- Group 1: 1+ digits|
- or([A-Z]+)
- Group 2: 1+ uppercase letters|
- or[a-z]+
- 1+ lowercase letters.