[英]Python regex to match word before extension
我有以下鏈接列表:
['/directory/index.html',
'/index.html',
'#',
'/index.html',
'/kss_how.html',
'dr_info/swearingenlarry.html',
'dr_info/swearingenlarrylast.html',
'dr_info/kingjohn.html',
'dr_info/kingjohnlast.html',
'dr_info/_coble.jpg',
'dr_info/coblebillielast.html',
'dr_info/netherystephen.jpg',
'dr_info/netherystephenlast.html',
'dr_info/rougeaupaul.jpg',
'dr_info/no_last_statement.html',
'dr_info/no_info_available.html',
'dr_info/no_last_statement.html',
'dr_info/no_last_statement.html']
我需要選擇類似的鏈接
'dr_info/kingjohn.html'
從中跳過其余部分。
到目前為止,我只想出了效率很低的解決方案:
p_1 = re.compile('dr.*(?<!last).html')
p_1_links = list(filter(p_1.match, links))
p_2 = re.compile('dr.*(?<!statement).html')
p_2_links = list(filter(p_2.match, p_1_links))
p_3 = re.compile('dr.*(?<!available).html')
valid_links = list(filter(p_3.match, p_2_links))
這讓我感到顫抖,我希望有人可以幫助我將其調整為一條線。
示例中的所需輸出將如下所示:
['dr_info/swearingenlarry.html',
'dr_info/kingjohn.html']
僅以dr_info
並以html
結尾的鏈接沒有以last
, no_last_statement
或no_info_available
采用
exceptions = ('last.html', 'statement.html', 'available.html')
links = [link for link in links if link.endswith('.html') and link.startswith('dr') and not link.endswith(exceptions)]
# => ['dr_info/swearingenlarry.html', 'dr_info/kingjohn.html']
參見Python演示
link.endswith('.html') and link.startswith('dr') and not link.endswith(exceptions)
過濾links
列表,保留所有以dr
開頭,以.html
結尾且不以任何值結尾的鏈接在exceptions
元組中。
出於教育目的,正則表達式解決方案可能看起來像
rx = re.compile(r'dr.*(?<!last)(?<!statement)(?<!available)\.html')
links = list(filter(rx.fullmatch, links))
您不能在以|
分隔的單個回溯中使用這三個異常。 交替運算符,因為Python lookbehinds是固定寬度的 。 .fullmatch
方法將確保整個字符串與正則表達式匹配,因此不需要錨。
為避免匹配的鏈接,其中排除的單詞緊接在dr
之后(如注釋中所述 ),並假設您只想匹配完整鏈接,則可以使用以下模式:
^dr(?!.*(?:last|statement|available)).*\.html$
您可以使用否定的Lookahead(而不是否定的Lookbehind),以便可以使用替代。 嘗試這樣的事情:
dr(?:.(?!last|statement|available))*\.html
正則表達式演示 。
Python示例:
import re
links = ['/directory/index.html',
'/index.html',
'#',
'/index.html',
'/kss_how.html',
'dr_info/swearingenlarry.html',
'dr_info/swearingenlarrylast.html',
'dr_info/kingjohn.html',
'dr_info/kingjohnlast.html',
'dr_info/_coble.jpg',
'dr_info/coblebillielast.html',
'dr_info/netherystephen.jpg',
'dr_info/netherystephenlast.html',
'dr_info/rougeaupaul.jpg',
'dr_info/no_last_statement.html',
'dr_info/no_info_available.html',
'dr_info/no_last_statement.html',
'dr_info/no_last_statement.html']
p_1 = re.compile('dr(?:.(?!last|statement|available))*\.html')
p_1_links = list(filter(p_1.match, links))
print(p_1_links)
輸出:
['dr_info/swearingenlarry.html', 'dr_info/kingjohn.html']
在線嘗試 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.