簡體   English   中英

使用正則表達式捕獲組 (Python)

[英]Capture groups with Regular Expression (Python)

這里有點菜鳥,如果我走錯了道歉。

我正在學習正則表達式,並且正在學習這一課: 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

謝謝!

您需要第一個捕獲的組:

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'

你也可以使用match[index]

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM