re.sub how to do it in one step?

后端 未结 1 1531
南方客
南方客 2021-01-23 16:53

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)


        
相关标签:
1条回答
  • 2021-01-23 17:12

    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.
    0 讨论(0)
提交回复
热议问题