Python Regex Sub - 在替换中使用匹配作为字典键 [英] Python Regex Sub - Use Match as Dict Key in Substitution
问题描述
我正在将一个程序从 Perl 翻译成 Python (3.3).我对 Python 相当陌生.在 Perl 中,我可以进行巧妙的正则表达式替换,例如:
I'm translating a program from Perl to Python (3.3). I'm fairly new with Python. In Perl, I can do crafty regex substitutions, such as:
$string =~ s/<(w+)>/$params->{$1}/g;
这将搜索 $string
,对于包含在 <> 中的每组单词字符,将使用正则表达式替换 $params
hashref匹配作为哈希键.
This will search through $string
, and for each group of word characters enclosed in <>, a substitution from the $params
hashref will occur, using the regex match as the hash key.
简洁地复制这种行为的最佳(Pythonic)方法是什么?我想出了一些类似的东西:
What is the best (Pythonic) way to concisely replicate this behavior? I've come up with something along these lines:
string = re.sub(r'<(w+)>', (what here?), string)
如果我能传递一个将正则表达式匹配到字典的函数可能会很好.这可能吗?
It might be nice if I could pass a function that maps regex matches to a dict. Is that possible?
感谢您的帮助.
推荐答案
您可以将一个可调用对象传递给 re.sub
以告诉它如何处理匹配对象.
You can pass a callable to re.sub
to tell it what to do with the match object.
s = re.sub(r'<(w+)>', lambda m: replacement_dict.get(m.group()), s)
使用 dict.get
允许您提供后备",如果所述词不在替换字典中,即
use of dict.get
allows you to provide a "fallback" if said word isn't in the replacement dict, i.e.
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
)时,当指定周围存在的东西时你想要的替代品,使用环视表达式通常更干净,这样你的比赛周围的东西就不会被替代.所以在这种情况下,我会写你的正则表达式
I'll note that when using re.sub
(and family, ie re.split
), when specifying stuff that exists around your wanted substitution, it's often cleaner to use lookaround expressions so that the stuff around your match doesn't get subbed out. So in this case I'd write your regex like
r'(?<=<)(w+)(?=>)'
否则,您必须在 lambda
中对括号进行一些拼接/拼接.为了清楚我在说什么,举个例子:
Otherwise you have to do some splicing out/back in of the brackets in your lambda
. To be clear what I'm talking about, an example:
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>'
这篇关于Python Regex Sub - 在替换中使用匹配作为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!