Capture groups with Regular Expression (Python)

PythonRegex

Python Problem Overview


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!

Python Solutions


Solution 1 - Python

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionL. RobinsonView Question on Stackoverflow
Solution 1 - PythonheemaylView Answer on Stackoverflow