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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48719537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:49:45  来源:igfitidea点击:

Capture groups with Regular Expression (Python)

pythonregex

提问by L. Robinson

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.

我正在学习正则表达式,正在学习本课: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?

在 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')

Returns

退货

file_record_transcript.pdf
file_07241999.pdf
Not found

But should return

但应该返回

file_record_transcript
file_07241999
Not found

Thanks!

谢谢!

回答by heemayl

You need the firstcaptured 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.

没有任何捕获的组规范作为参数group(),它将显示完整的匹配,就像你现在得到的一样。

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'