user1755071
user1755071

Reputation: 3819

How can i grab the matched regex pattern in python

I have this code and its not working

import re
mystring = "This is my test the string to match the stuff"    
p = re.compile(" the ")

Now I want to able to put the first match found in var1 and second match in var2

Upvotes: 0

Views: 122

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

You mean something like this?

In [3]: import re

In [4]: strs= "This is my test the string to match the stuff"

In [5]: p = re.compile(" the ")

In [6]: re.findall(p,strs)
Out[6]: [' the ', ' the ']

In [7]: var1,var2=re.findall(p,strs)

In [8]: var1,var2
Out[8]: (' the ', ' the ')

In case the number of matches returned are more than 2, then you've slice the list first.

var1,var2=[' the ', ' the ',' the '][:2]

On python 3.x you can take the advantage of the * to grab the rest of the elements in a list:

In [2]: var1,var2,*extras=[' the ', ' the ','foo','bar']

In [3]: var1
Out[3]: ' the '

In [4]: var2
Out[4]: ' the '

In [5]: extras             #rest of the elements are stored in extras
Out[5]: ['foo', 'bar']

Upvotes: 4

Related Questions