Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

regex - Capture groups with Regular Expression (Python)

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...