How can I get part of regex match as a variable in python?


In Perl it is possible to do something like this (I hope the syntax is right...):

$string =~ m/lalala(I want this part)lalala/;
$whatIWant = $1;

I want to do the same in Python and get the text inside the parenthesis in a string like $1.

11/26/2009 12:07:14 AM

Accepted Answer

See: Python regex match objects

>>> import re
>>> p = re.compile("lalala(I want this part)lalala")
>>> p.match("lalalaI want this partlalala").group(1)
'I want this part'
8/13/2014 10:28:47 AM

If you want to get parts by name you can also do this:

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
>>> m.groupdict()
{'first_name': 'Malcom', 'last_name': 'Reynolds'}

The example was taken from the re docs

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow