【问题标题】:python: Search string in a mutable stringpython:在可变字符串中搜索字符串
【发布时间】:2016-07-04 01:40:38
【问题描述】:

我有一个非常长且可变的字符串。 像这样:

s = "hello today we see there? Otherwise are available tuesday 10:00 to 18:00. OK?"

或者这个:

s = "hello today we see there? Otherwise are available tue 10.00 to 18.00. OK?"

我想作为输出:

tuesday 10:00 to 18:00

或者:

tue 10.00 to 18.00

我试过了:

print re.findall("(tuesday|tue \s\d+:|.\d+\s-\s\d+:|.\d+)",s)[0]

但它不正确。

【问题讨论】:

  • 你实际上没有可变字符串,因为 Python 字符串是不可变的。

标签: python regex string findall


【解决方案1】:

您可以按以下方式修复模式:

tue(?:sday)?\s*\d{1,2}[:.]\d{2}\s*(?:-|to)\s*\d+[:.]\d+

regex demo

请注意,您不需要使用交替,也不需要捕获组。

  • tue(?:sday)? - tuetuesday
  • \s* - 0+ 个空格符号
  • \d{1,2} - 两位数或一位数
  • [:.] - :.
  • \d{2} - 正好 2 位数
  • \s* - 0+ 个空格
  • (?:-|to) - :to(请注意,(?:...) 是非捕获组,因此 re.findall 无法在结果中返回它)
  • \s*\d+[:.]\d+ - 0+ 空格后跟时间(可以写成前一个,但很可能这也可以),\d+ 匹配 1 个或多个数字。

Python demo:

import re
p = re.compile(r'tue(?:sday)?\s*\d{1,2}[:.]\d{2}\s*(?:-|to)\s*\d+[:.]\d+')
test_str = "hello today we see there? Otherwise are available tuesday 10:00 to 18:00. OK?\nhello today we see there? Otherwise are available tue 10.00 to 18.00. OK?"
print(p.findall(test_str))
# => ['tuesday 10:00 to 18:00', 'tue 10.00 to 18.00']

【讨论】:

    猜你喜欢
    • 2016-11-30
    • 1970-01-01
    • 2019-10-06
    • 2012-07-23
    • 1970-01-01
    相关资源
    最近更新 更多