tags:

views:

109

answers:

6

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.

+2  A: 
import re
data = "some input data"
m = re.search("some (input) data", data)
if m: # "if match was successful" / "if matched"
  print m.group(1)

Check the docs for more.

Roger Pate
+1  A: 
import re
match = re.match('lalala(I want this part)lalala', 'lalalaI want this partlalala')
print match.group(1)
Mark Byers
+3  A: 

See: python regex grouping

>>> import re
>>> p = re.compile("lalala(I want this part)lalala")
>>> p.match("lalalaI want this partlalala").group(1)
'I want this part'
The MYYN
+2  A: 

.

import re
astr='lalalabeeplalala'
match=re.search('lalala(.*)lalala',astr)
whatIWant=match.group(1) if match else None
print(whatIWant)

A small note: in Perl, when you write

$string =~ m/lalala(.*)lalala/;

the regexp can match anywhere in the string. The equivalent is accomplished with the re.search() function, not the re.match() function, which requires that the pattern match starting at the beginning of the string.

unutbu
+1  A: 

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

Nadia Alramli
+1  A: 

there's no need for regex. think simple.

>>> "lalala(I want this part)lalala".split("lalala")
['', '(I want this part)', '']
>>> "lalala(I want this part)lalala".split("lalala")[1]
'(I want this part)'
>>>