![](/img/trans.png)
[英]python regex re.sub: remove everything before or after a pattern until find a specific condition in both ways
[英]Use Regex re.sub to remove everything before and including a specified word
我有一個字符串,看起來像“Blah blah blah,Updated:2012年8月23日”,我希望使用正則表達式來提取Aug. 23, 2012
的日期。 我發現堆棧中的一篇文章有類似的東西: 正則表達式刪除一個字符前的所有文本 ,但是當我嘗試時它也不起作用
date_div = "Blah blah blah, Updated: Aug. 23, 2012"
extracted_date = re.sub('^[^Updated]*',"", date_div)
我怎樣才能刪除所有內容,包括更新內容,以便僅剩下Aug. 23, 2012
?
謝謝!
在這種情況下,您可以使用正則表達式執行此操作,例如:
>>> date_div = "Blah blah blah, Updated: Aug. 23, 2012"
>>> date_div.split('Updated: ')
['Blah blah blah, ', 'Aug. 23, 2012']
>>> date_div.split('Updated: ')[-1]
'Aug. 23, 2012'
你可以使用Lookahead:
import re
date_div = "Blah blah blah, Updated: Aug. 23, 2012"
extracted_date = re.sub('^(.*)(?=Updated)',"", date_div)
print extracted_date
OUTPUT
Updated: Aug. 23, 2012
編輯
如果下面的MattDMo評論是正確的,你想要刪除“更新:”,你可以這樣做:
extracted_date = re.sub('^(.*Updated: )',"", date_div)
使用正則表達式,您可以使用兩個正則表達式,具體取決於單詞的出現次數:
# Remove all up to the first occurrence of the word including it (non-greedy):
^.*?word
# Remove all up to the last occurrence of the word including it (greedy):
^.*word
^
匹配字符串位置的開頭, .*?
匹配任何0+字符(注意使用re.DOTALL
標志,以便.
可以匹配換行符)盡可能少 ( .*
盡可能多地匹配)然后word
匹配和消耗(即添加到匹配並推進正則表達式)索引)這個詞。
注意,這里使用的re.escape(up_to_word)
如果你的up_to_word
並不是由唯一的字母數字和下划線字符,它是使用更安全re.escape
使特殊字符像(
, [
, ?
等無法阻止的正則表達式從找到有效的匹配。
查看Python演示 :
import re
date_div = "Blah blah\nblah, Updated: Aug. 23, 2012 Blah blah Updated: Feb. 13, 2019"
up_to_word = "Updated:"
rx_to_first = r'^.*?{}'.format(re.escape(up_to_word))
rx_to_last = r'^.*{}'.format(re.escape(up_to_word))
print("Remove all up to the first occurrence of the word including it:")
print(re.sub(rx_to_first, '', date_div, flags=re.DOTALL).strip())
print("Remove all up to the last occurrence of the word including it:")
print(re.sub(rx_to_last, '', date_div, flags=re.DOTALL).strip())
輸出:
Remove all up to the first occurrence of the word including it:
Aug. 23, 2012 Blah blah Updated: Feb. 13, 2019
Remove all up to the last occurrence of the word including it:
Feb. 13, 2019
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.