使用Regex re.sub删除指定单词之前及包含该单词的所有内容



我有一个字符串,看起来像"Blah Blah Blah, Updated: 8月23日,2012",从中我想使用Regex提取日期Aug. 23, 2012。我在堆栈中发现了一篇类似的文章:regex删除字符之前的所有文本,但当我尝试

时,这也不起作用
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'

对于正则表达式,您可以根据单词的出现情况使用两个正则表达式:

# 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匹配并消耗(即添加到匹配并推进regex索引)单词。

注意re.escape(up_to_word)的使用:如果您的up_to_word不是由单一的字母数字和下划线字符组成,则使用re.escape更安全,以便(, [, ?等特殊字符不能阻止regex找到有效匹配。

参见Python演示:

import re
date_div = "Blah blahnblah, 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

您可以使用向前看:

import re
date_div = "Blah blah blah, Updated: Aug. 23, 2012"
extracted_date = re.sub('^(.*)(?=Updated)',"", date_div)
print extracted_date

Updated: Aug. 23, 2012

编辑
如果MattDMo下面的评论是正确的,你也想删除"Update:",你可以这样做:

extracted_date = re.sub('^(.*Updated: )',"", date_div)

相关内容

最新更新