【问题标题】:Removing time expressions from a string从字符串中删除时间表达式
【发布时间】:2017-04-12 12:20:17
【问题描述】:

我在编写函数时遇到问题。目标是输入一个字符串:

'from 16:00-17:00 we will be bowling and from 18:00-19:00 there is dinner'

它应该返回一个带有[16:00-17:00, 18:00-19:00]的列表

我想为此使用regex,并使用re.findall 搜索时间模式。但是我无法让它工作。

有人有什么建议吗?

【问题讨论】:

  • 你试过什么?你能告诉我们你的代码和你的尝试吗?
  • 快速提示:1/。 \d 匹配任何十进制数字。相当于 [0-9]。 2/。 a{3} 精确匹配 3 个连续的 a 字符。有了这个基础,您应该能够快速完成您的正则表达式。 3/。这是quick testing zone 我知道您需要一个解决方案,但请您发送tour 并阅读有关How to Ask 的更多信息。
  • re.findall(r'(\d{2}:\d{2}-\d{2}:\d{2})(?is)',s)

标签: python regex string time


【解决方案1】:

你应该学习how to ask a good question。不过因为我也在学习正则表达式,所以我可以为你回答这个问题......

您可以使用该模式:\d{2}\:\d{2}\-\d{2}\:\d{2}

  • \d{2} 匹配出现 2 次的数字(等于 [0-9])
  • \: 匹配字符 : 字面意思(区分大小写)
  • \- 匹配字符 - 字面意思(区分大小写)

代码:

import re

strs = ['from 16:00-17:00 we will be bowling and from 18:00-19:00 there is dinner',
    'from 12:00-14:00 we will be bowling and from 15:00-17:00 there is dinner',
    'from 10:00-16:30 we will be bowling and from 18:30-18:45 there is dinner']

pat = '\d{2}\:\d{2}\-\d{2}\:\d{2}'

for s in strs:
    times = re.findall(pat, s)
    print(times)

输出:

['16:00-17:00', '18:00-19:00']
['12:00-14:00', '15:00-17:00']
['10:00-16:30', '18:30-18:45']

Regex Example

【讨论】:

  • 我以为我们会先让他自己测试。西部最快的枪通过分散我的注意力而获胜!
猜你喜欢
  • 1970-01-01
  • 2021-09-07
  • 2021-01-17
  • 2014-06-20
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 2018-01-28
  • 2017-08-24
相关资源
最近更新 更多