我是Python的新手,经过任何可能的帮助。下面是我尝试提取 2 个子字符串的示例文本字符串:
- 位置
- 时间戳
示例文本:您在皇冠街的预订 - 6 月 29 日下午 1:00
位置子字符串介于以下 2 个短语之间,分别是常量"您的预订"和"-"。短语中包含的空格是故意的。在此示例中,我所需的输出字符串是皇冠街。提供此结果的最佳 Python 正则表达式是什么?
时间戳子字符串处理字符串中的"-"表达式。在此示例中,我所需的输出字符串是6 月 29 日下午 1:00。提供此结果的最佳 Python 正则表达式是什么?
import re
example = 'Your booking at Crown Street - June 29th, 1:00pm'
regex = re.compile(r'Your booking at (?P<location>.+) - (?P<timestamp>.+)$')
print(regex.match(example).groupdict())
输出
{'location': 'Crown Street', 'timestamp': 'June 29th, 1:00pm'}
请注意,如果位置名称中有-
,则最终可能会以错误匹配结束;如果您始终确定时间戳将有一个英语月份开始,则可以使用(?P<timestamp>(?:Jan|Feb|Mar|...).+)
。
使用re.search
演示:
import re
text = "Your booking at Crown Street - June 29th, 1:00pm"
data = re.search("Your booking ats+(.*)s+-s+(.*)", text)
if data:
print(data.group(1))
print(data.group(2))
输出:
Crown Street
June 29th, 1:00pm