3

My regex needs to match two words in a sentence, but only the second word needs to be replaced. The first word is actually a key to a dictionary where the substitute for the second word is fetched. In PERL it would look something like:

$sentence = "Tom's boat is blue";
my %mydict = {}; # some key-pair values for name => color
$sentence =~ s/(\S+)'s boat is (\w+)/$1's boat is actually $mydict{$1}/;
print $sentence;

How can this be done in python?

1 Answer 1

3

Something like this:

>>> sentence = "Tom's boat is blue"
>>> mydict = { 'Tom': 'green' }
>>> import re
>>> re.sub("(\S+)'s boat is (\w+)", lambda m: "{}'s boat is actually {}".format(m.group(1), mydict[m.group(1)]), sentence)
"Tom's boat is actually green"
>>> 

though it would look better with the lambda extracted to a named function.

Sign up to request clarification or add additional context in comments.

1 Comment

It worked perfectly, but I wonder why it is so much less intuitive than in Perl, quite contrary to my experience with Python so far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.