使用正则表达式(Python)捕获组

74

我有点新手,如果我做错了什么请见谅。

我正在学习正则表达式,并且正在学习这个课程:https://regexone.com/lesson/capturing_groups

在Python解释器中,我尝试使用括号只捕获搜索字符串中.pdf部分之前的内容,但我的结果尽管使用了括号,但仍然将其捕获。我做错了什么?

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')
返回
file_record_transcript.pdf
file_07241999.pdf
Not found

但应该返回

file_record_transcript
file_07241999
Not found

谢谢!

2个回答

96

您需要获取第一个捕获组:

a.group(1)
b.group(1)
...
没有将任何捕获组指定为 group() 的参数,它将显示完整的匹配结果,就像您现在所看到的一样。
这里是一个例子:
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'

7
哇,第一个捕获组是1而不是0?好的,知道了! - Anson Savage

3

你还可以使用match[index]

a[0] => Full match (file_record_transcript.pdf)
a[1] => First group (file_record_transcript)
a[2] => Second group (if any)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接