Chet
Chet

Reputation: 1269

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']

Upvotes: 6

Views: 247

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

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']

Upvotes: 3

Barmar
Barmar

Reputation: 780974

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'.

Upvotes: 1

Related Questions