I've just made the switch from Perl to Python and am disappointed by the re module. I'm looking for the equivalent of $1 in Python, or any other special variables in regular expressions. In Perl I would use this:
$_ =
I'm trying to do the same in Python. Thanks!"<name>Joe</name>";
s/<(.)>(.)<[/]
(.*)>/$2/;
$1 equals the text " brown ".
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
You can also use the \2
in the back ref or match group in Python.
Such as this:
>>> re.sub(r'(\w+) (\w+)',r'\2 \1','Joe Bob')
'Bob Joe'
Or named substitutions (a Python innovation later ported to Perl):
>>> re.sub(r'(?P<First>\w+) (?P<Second>\w+)',r'\g<Second> \g<First>','Joe Bob')
'Bob Joe'
>>> ma=re.search(r'(?P<First>\w+) (?P<Second>\w+)','George Bush')
>>> ma.group(1)
'George'
>>> ma.group('Second')
'Bush'
But, admittedly, Python re module is a little weak in comparison to recent Perl's.
For a first class regex module, install the newer regex module. It is scheduled to by part of Python 3.4 and is very good.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With