mar*_*eau 7 python regex substitution
我想替换字符串中匹配的 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))
Run Code Online (Sandbox Code Playgroud)
输出:
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))
Run Code Online (Sandbox Code Playgroud)
然而,从文档中,听起来我应该能够通过向它传递一个替换字符串来获得相同的结果,其中包含对其中命名组的引用。然而,我这样做的尝试没有奏效,因为有时一个组是不匹配的,并且为它返回的值是None(而不是空字符串'')。
cleaned = re.sub(pattern, r'\g<text>\g<content>', my_str)
print('cleaned: {!r}'.format(cleaned))
Run Code Online (Sandbox Code Playgroud)
输出:
cleaned: "Here's some sample stuff in the middle of some other text."
Run Code Online (Sandbox Code Playgroud)
我做错了什么或不理解?
def repl(matchobj):
if matchobj.group(3):
return matchobj.group(1)+matchobj.group(3)
else:
return matchobj.group(1)
my_str = "Here's some <first>sample stuff</first> in the " \
"<second>middle</second> of some other text."
pattern = r'(?P<text>.*?)(?:<(?P<tag>\w+)>(?P<content>.*)</(?P=tag)>|$)'
print re.sub(pattern, repl, my_str)
Run Code Online (Sandbox Code Playgroud)
您可以使用 的调用功能re.sub。
编辑:
cleaned = re.sub(pattern, r'\g<text>\g<content>', my_str)当字符串的最后一位匹配时,这将不起作用,即of some other text.有\g<text>定义但没有,\g<content>因为没有内容。但你仍然要求re.sub这样做。所以它会产生错误。如果你使用字符串,"Here's some <first>sample stuff</first> in the <second>middle</second>"那么你print re.sub(pattern,r"\g<text>\g<content>", my_str)将工作\g<content>在这里一直被定义。
| 归档时间: |
|
| 查看次数: |
6127 次 |
| 最近记录: |