簡體   English   中英

使用Regex re.sub刪除包含指定單詞之前的所有內容

[英]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.

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