【发布时间】:2015-02-22 01:57:53
【问题描述】:
我想替换字符串中匹配的 re 模式的文本,可以使用 re.sub() 来完成。如果我在调用中将函数作为 repl 参数传递给它,它会按需要工作,如下所示:
from __future__ import print_function
import re
pattern = r'(?P<text>.*?)(?:<(?P<tag>\w+)>(?P<content>.*)</(?P=tag)>|$)'
my_str = "Here's some <first>sample stuff</first> in the " \
"<second>middle</second> of some other text."
def replace(m):
return ''.join(map(lambda v: v if v else '',
map(m.group, ('text', 'content'))))
cleaned = re.sub(pattern, replace, my_str)
print('cleaned: {!r}'.format(cleaned))
输出:
cleaned: "Here's some sample stuff in the middle of some other text."
但是从文档看来,我应该能够通过将替换字符串传递给它并引用其中的命名组来获得相同的结果。但是我尝试这样做并没有奏效,因为有时一个组是不匹配的,并且为它返回的值是None(而不是一个空字符串'')。
cleaned = re.sub(pattern, r'\g<text>\g<content>', my_str)
print('cleaned: {!r}'.format(cleaned))
输出:
Traceback (most recent call last):
File "test_resub.py", line 21, in <module>
cleaned = re.sub(pattern, r'\g<text>\g<content>', my_str)
File "C:\Python\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Python\lib\re.py", line 278, in filter
return sre_parse.expand_template(template, match)
File "C:\Python\lib\sre_parse.py", line 802, in expand_template
raise error, "unmatched group"
sre_constants.error: unmatched group
我做错了什么或不理解?
【问题讨论】:
-
最后一场比赛的
content是None... -
@KennyTM:我知道一些匹配组将是
None,这就是我在replace()函数中使用lambda v: v if v else ''的原因。替换字符串中是否需要类似的东西,如果需要,它是如何完成的?
标签: python regex substitution