Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

Python Regex Sub - Use Match as Dict Key in Substitution

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;

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.

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?

Thanks for the help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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

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+)(?=>)'

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>'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...