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