Capture groups with Regular Expression (Python)

Question:

Kind of a noob here, apologies if I misstep.

I’m learning regular expressions and am on this lesson:
https://regexone.com/lesson/capturing_groups.

In the python interpreter, I try to use the parentheses to only capture what precedes the .pdf part of the search string but my result captures it despite using the parens. What am I doing wrong?

import re
string_one = 'file_record_transcript.pdf'
string_two = 'file_07241999.pdf'
string_three = 'testfile_fake.pdf.tmp'

pattern = '^(file.+).pdf$'
a = re.search(pattern, string_one)
b = re.search(pattern, string_two)
c = re.search(pattern, string_three)

print(a.group() if a is not None else 'Not found')
print(b.group() if b is not None else 'Not found')
print(c.group() if c is not None else 'Not found')

Returns

file_record_transcript.pdf
file_07241999.pdf
Not found

But should return

file_record_transcript
file_07241999
Not found

Thanks!

Asked By: L. Robinson

||

Answers:

You need the first captured group:

a.group(1)
b.group(1)
...

without any captured group specification as argument to group(), it will show the full match, like what you’re getting now.

Here’s an example:

In [8]: string_one = 'file_record_transcript.pdf'

In [9]: re.search(r'^(file.*).pdf$', string_one).group()
Out[9]: 'file_record_transcript.pdf'

In [10]: re.search(r'^(file.*).pdf$', string_one).group(1)
Out[10]: 'file_record_transcript'
Answered By: heemayl

you can also use match[index]

a[0] => Full match (file_record_transcript.pdf)
a[1] => First group (file_record_transcript)
a[2] => Second group (if any)
Answered By: uingtea
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.