【问题标题】:Python Regex Sub - Use Match as Dict Key in SubstitutionPython Regex Sub - 在替换中使用匹配作为字典键
【发布时间】:2014-04-28 00:21:29
【问题描述】:

我正在将一个程序从 Perl 翻译成 Python (3.3)。我对 Python 很陌生。在 Perl 中,我可以进行巧妙的正则表达式替换,例如:

$string =~ s/<(\w+)>/$params->{$1}/g;

这将搜索$string,并且对于包含在 中的每一组单词字符,将使用正则表达式匹配作为哈希键替换$params 哈希引用。

简洁地复制这种行为的最佳(Pythonic)方法是什么?我想出了一些类似的东西:

string = re.sub(r'<(\w+)>', (what here?), string)

如果我可以传递一个将正则表达式匹配到字典的函数,那可能会很好。这可能吗?

感谢您的帮助。

【问题讨论】:

  • 如果输入包含&lt;weird&gt; stuff&gt;,会发生什么/你想发生什么? IE。你对输入语法有什么假设?

标签: python regex perl python-3.x


【解决方案1】:

您可以将一个可调用对象传递给re.sub,告诉它如何处理匹配对象。

s = re.sub(r'<(\w+)>', lambda m: replacement_dict.get(m.group()), s)

dict.get 的使用允许您在替换字典中没有所述单词时提供“后备”,即

lambda m: replacement_dict.get(m.group(), m.group()) 
# fallback to just leaving the word there if we don't have a replacement

我会注意到,当使用re.sub(和家庭,即re.split)时,当指定存在周围您想要替换的东西时,使用环视表达式通常更干净,这样你的比赛周围的东西不会被替换掉。所以在这种情况下,我会像这样写你的正则表达式

r'(?<=<)(\w+)(?=>)'

否则,您必须在lambda 中的括号内进行一些拼接。为了清楚我在说什么,举个例子:

s = "<sometag>this is stuff<othertag>this is other stuff<closetag>"

d = {'othertag': 'blah'}

#this doesn't work because `group` returns the whole match, including non-groups
re.sub(r'<(\w+)>', lambda m: d.get(m.group(), m.group()), s)
Out[23]: '<sometag>this is stuff<othertag>this is other stuff<closetag>'

#this output isn't exactly ideal...
re.sub(r'<(\w+)>', lambda m: d.get(m.group(1), m.group(1)), s)
Out[24]: 'sometagthis is stuffblahthis is other stuffclosetag'

#this works, but is ugly and hard to maintain
re.sub(r'<(\w+)>', lambda m: '<{}>'.format(d.get(m.group(1), m.group(1))), s)
Out[26]: '<sometag>this is stuff<blah>this is other stuff<closetag>'

#lookbehind/lookahead makes this nicer.
re.sub(r'(?<=<)(\w+)(?=>)', lambda m: d.get(m.group(), m.group()), s)
Out[27]: '<sometag>this is stuff<blah>this is other stuff<closetag>'

【讨论】:

    猜你喜欢
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 2020-09-01
    相关资源
    最近更新 更多