有没有办法完全反向匹配我使用的正则表达式。
(?!...)
仅适用于简单模式。我的意思是我有一个RegEx来匹配多种格式,但我想替换除多种格式之外的字符串中的所有内容。
比如说:我写了一个复杂的RegEx模式来查找工作日,小时,月,年。而不是找到这些匹配并使用这些模式拆分我的字符串并加入匹配的所有内容;如果有反向匹配,我可以直接替换它。
How to "inverse match" with regex?中给出的解决方案并不支持所有内容。
示例
hr = """
Monday: 11:30am - 9:30pm Tuesday: 11:30am - 9:30pm
Wednesday: 11:30am - 10:00pm Thursday: 11:30am - 10:00pm
Friday: 11:30am - 10:30pm Saturday: 11:00am - 10:30pm
(brunch served until 3pm) Sunday: 10:30am - 9:30pm (brunch served until 3pm)
Happy Hour and Special Appetizer menu starting at $3 in the bar. Hours from 4 - 7pm Daily.
$4 BURGER special available on Monday. Wednesday: 1/2 off all bottled wines (4-close)"""
import re
newStr = []
dayPattern = """
(?:mon|tue|wed|thu|fri|sat|sun|thurs)(?:day)?(?:[.:])*
\s*
(?:\d{1,2}(?:[:]\d{1,2})?)\s*(?:[ap][.]?m.?) # Start hour
\s*[-|to]+\s*
(?:\d{1,2}(?:[:]\d{1,2})?)\s*(?:[ap][.]?m.?) # Close hour
"""
newStr.extend(\
re.findall(re.compile(dayPattern, re.VERBOSE|re.IGNORECASE), hr))
print " ".join(newStr)
输出
Monday: 11:30am - 9:30pm Thursday: 11:30am - 10:00pm Friday: 11:30am - 10:30pm Sunday: 10:30am - 9:30pm
但在这里我缺少"Monday: 11:30am - 9:30pm Tuesday: 11:30am - 9:30pm Wednesday: 11:30am - 10:00pm Thursday: 11:30am - 10:00pm Friday: 11:30am - 10:30pm"
。
我可以修改我的正则表达式以包含此模式
但是除了星期一/星期二之外,有没有办法可以删除任何单词....&周一/周二/周三......& 11:00 am/12pm ...
,即我想要的是这个输出:
Monday: 11:30am - 9:30pm Tuesday: 11:30am - 9:30pm Wednesday:
11:30am - 10:00pm Thursday: 11:30am - 10:00pm Friday: 11:30am - 10:30pm
Saturday: 11:00am - 10:30pm Sunday: 10:30am - 9:30pm
答案 0 :(得分:0)
我不明白你做反向正则表达式的意图。 findall()
似乎是选择时间的自然方式,如下所示:
' '.join(re.findall(r'\w{3,6}day:\s*\d{1,2}:\d{1,2}[ap]m\s*-\s*\d{1,2}:\d{1,2}[ap]m', hr))
它产生:
'Monday: 11:30am - 9:30pm Tuesday: 11:30am - 9:30pm Wednesday: 11:30am - 10:00pm Thursday: 11:30am - 10:00pm Friday: 11:30am - 10:30pm Saturday: 11:00am - 10:30pm Sunday: 10:30am - 9:30pm'