Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the Python equivalent of $1 in Perl, or any other special variables in regular expressions?

Tags:

python

regex

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: $_ = "<name>Joe</name>"; s/<(.)>(.)<[/](.*)>/$2/; I'm trying to do the same in Python. Thanks!

like image 705
user1510648 Avatar asked Aug 11 '12 02:08

user1510648


People also ask

What is the meaning of $1 in Perl regex?

$1 equals the text " brown ".

What does $1 do in regex?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

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.

like image 105
dawg Avatar answered Oct 23 '22 05:10

dawg