[Tutor] Regex question
Steve Willoughby
steve at alchemy.com
Wed Mar 30 09:16:29 CEST 2011
On 29-Mar-11 23:55, Alan Gauld wrote:
> ""Andrés Chandía"" <andres at chandia.net> wrote
>> in perl there is a way to reference previous registers,
>> $text =~ s/<u>(l|L|n|N)<\/u>/$1e/g;
>
>> I'm looking for the way to do it in python
If you're using just a straight call to re.sub(), it works like this:
text = re.sub(r'<u>(l|L|n|N)</u>', '\1e', text)
You use \1, \2, etc. for backreferences just like all the other
regex-based editors do (Perl's more of an exception than the rule there).
Alternatively, you can pre-compile the regular expression into an object:
pattern = re.compile(r'<u>(l|L|n|N)</u>')
and then substitute by calling its sub() method:
text = pattern.sub('\1e', text)
--
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53
More information about the Tutor
mailing list