Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

regex - re.sub how to do it in one step?

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)

Does anybody knows how to make from such strings as XXxxxx999 --> Xx9.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...