【问题标题】:Capture groups with Regular Expression (Python)使用正则表达式捕获组 (Python)
【发布时间】:2018-07-21 00:47:27
【问题描述】:

这里有点菜鸟,如果我走错了道歉。

我正在学习正则表达式,并且正在学习这一课: 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

谢谢!

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您需要第一个捕获的组:

    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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-12
      • 2019-03-17
      • 2021-01-30
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      相关资源
      最近更新 更多