re.sub 如何一步完成? [英] re.sub how to do it in one step?
本文介绍了re.sub 如何一步完成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试将这些步骤合二为一,但它不起作用
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)
有谁知道如何从XXxxxx999
--> Xx9
.
Does anybody knows how to make from such strings as XXxxxx999
--> Xx9
.
推荐答案
您可以使用回调方法作为替换参数,如下所示:
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
请参阅 Python 演示.
正则表达式匹配:
([0-9]+)
- 第 1 组:1+ 位数|
- 或([A-Z]+)
- 第 2 组:1+ 个大写字母|
- 或[a-z]+
- 1+ 个小写字母.
([0-9]+)
- Group 1: 1+ digits|
- or([A-Z]+)
- Group 2: 1+ uppercase letters|
- or[a-z]+
- 1+ lowercase letters.
这篇关于re.sub 如何一步完成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文