Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex in Python - Using groups

I am new to regex, why does this not output 'present'?

tale = "It was the best of times, ... far like the present ... of comparison only. "
a = re.compile('p(resent)')
print a.findall(tale)

>>>>['resent']
like image 451
Chet Avatar asked Dec 25 '12 02:12

Chet


2 Answers

try something like this if you're trying to match the exact word present here:

In [297]: tale="resent present ppresent presentt"

In [298]: re.findall(r"\bpresent\b",tale)
Out[298]: ['present']
like image 81
Ashwini Chaudhary Avatar answered Nov 03 '22 07:11

Ashwini Chaudhary


From the Python documentation

If one or more groups are present in the pattern, return a list of groups

If you want it to just use the group for grouping, but not for capturing, use a non-capture group:

a = re.compile('p(?:resent)')

For this regular expression, there's no point in it, but for more complex regular expressions it can be appropriate, e.g.:

a = re.compile('p(?:resent|eople)')

will match either 'present' or 'people'.

like image 38
Barmar Avatar answered Nov 03 '22 07:11

Barmar