Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 412
Lucas Avatar asked Nov 26 '09 00:11

Lucas


People also ask

How do I find a match string in Python?

It returns a Boolean (either True or False ). To check if a string contains a substring in Python using the in operator, we simply invoke it on the superstring: fullstring = "StackAbuse" substring = "tack" if substring in fullstring: print("Found!") else: print("Not found!")

How do you replace all occurrences of a regex pattern in a string in Python?

sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.


2 Answers

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

like image 79
Nadia Alramli Avatar answered Nov 21 '22 19:11

Nadia Alramli


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' 
like image 33
miku Avatar answered Nov 21 '22 20:11

miku