[英]Regular expression to extract all the word after a specific symbol in a word using python
[英]How do I get all the dates or keywords of particular patterns before specific word using regular expression in python?
我有以下字符串,我需要在關鍵字整體生產之前的所有年份范圍(例如 2018-19)。
Details Unit/ Base 2017-18 2018-19 June (P) April-June (P)\\r\\n (P) 2018-19 2019-20 2018-19 2019-20\\r\\n overall production 2014-15 2015-16 monthly production
我試過:
re.findall(r"(\d{4}-\d{2})", string)
這讓我回歸: ['2017-18', '2018-19', '2018-19', '2019-20', '2018-19', '2019-20', '2014-15', '2015-16']
。 在這里我不想要過去兩年的'2014-15', '2015-16'
因為它是在關鍵字整體生產之后出現的
我也試過:
re.findall(r"(\d{4}-\d{2}).+overall production", string)
但我只得到第一年的范圍['2017-18']
有人可以幫我寫一個正確的正則表達式,以便我在我通過的特定關鍵字之前獲得所有年份范圍(不考慮計數)。
第二次嘗試中的.+overall production
消耗所有文本,包括overall production
,這就是為什么只返回第一個范圍(在此匹配之后沒有第二個overall production
子字符串)。
您可以使用基於前瞻的解決方案:
re.findall(r'\b\d{4}-\d{2}\b(?=.*overall production)', text, re.DOTALL)
查看正則表達式演示
細節
\\b
- 詞邊界\\d{4}-\\d{2}
- 四位數字, -
, 兩位數字\\b
- 單詞邊界(?=.*overall production)
- 一個正向前瞻,需要(並且不消耗,即它不會使正則表達式索引隨着匹配而移動,並且不會添加與整體匹配值匹配的文本)任何 0+ 個字符,盡可能多,緊跟在當前位置右側的overall production
子串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.