不能在匹配的组上使用字符串的方法

时间:2013-05-15 11:52:28

标签: python regex

我正在行使一个标准的正则表达式:

Bill Gates → GATES, Bill

所以我这样做:

In [21]: re.sub("([^ ]+) (.+)", r"\2".upper() + r", \1", "Bill Gates")
Out[21]: 'Gates, Bill'

为什么它不起作用?如何将字符串方法应用于匹配的字符串?

1 个答案:

答案 0 :(得分:3)

您是替换模式的大写(部分),而不是实际的替换结果

r"\2".upper() + r", \1"表达式会在将其传递给"\\2, \\1"之前产生值re.sub()

要动态处理匹配组,您需要在传递给.sub()的函数中应用更改,而不是替换模式:

def uppercase_last(match):
    return "{}, {}".format(match.group(2).upper(), match.group(1))

re.sub("([^ ]+) (.+)", uppercase_last, "Bill Gates")

演示:

>>> import re
>>> def uppercase_last(match):
...     return "{}, {}".format(match.group(2).upper(), match.group(1))
... 
>>> re.sub("([^ ]+) (.+)", uppercase_last, "Bill Gates")
'GATES, Bill'

或者,根本不要使用正则表达式:

>>> name = 'Bill Gates'
>>> first, rest = name.split(None, 1)
>>> "{}, {}".format(rest.upper(), first)