【问题标题】:Python Regex pattern match of a string字符串的 Python 正则表达式模式匹配
【发布时间】:2017-08-07 21:36:18
【问题描述】:

什么是字符串中模式的正则表达式:

description details #lo firstname lastname 29 March 2017

因此,正则表达式需要识别四个字段:描述、优先级、名称和日期。

我成功匹配了第一个字符串:

^([^#]*).

但是,我不知道如何匹配其他字段。

谢谢。

【问题讨论】:

  • 你能展示你尝试过的东西吗?如果您表明您已努力解决自己的问题,用户将更有可能为您提供帮助
  • 感谢您的建议!
  • 名字被捕获但姓氏未被捕获。另外,如果日期的月份是字符串而不是数字,我该怎么办?非常感谢@WiktorStribiżew

标签: python regex


【解决方案1】:

看来你可以用

^(?P<description>[^#]+?)\s+#(?P<priority>\w+)\s+(?P<name>.*?)\s+(?P<date>\d.*)$

见regex demo

详情

  • ^ - 字符串的开头(如果与 re.match / re.fullmatch 一起使用,则为隐式)
  • (?P&lt;description&gt;[^#]+?) - 组“描述”:# 以外的一个或多个字符尽可能少
  • \s+ - 1+ 个空格
  • # - 一个 # 字符
  • (?P&lt;priority&gt;\w+) - 匹配 1 个以上单词字符的组“优先级”
  • \s+ - 1+ 个空格
  • (?P&lt;name&gt;.*?) - 除换行符以外的任何 0+ 字符,尽可能少
  • \s+ - 1+ 个空格
  • (?P&lt;date&gt;\d.*) - 组“日期”:一个数字和该行的其余部分
  • $ - 字符串结尾(隐含在 re.fullmatch 中)

注意:re.fullmatch 在 Python 3.x 中可用。

Python demo:

import re
rx = r"(?P<description>[^#]+?)\s+#(?P<priority>\w+)\s+(?P<name>.*?)\s+(?P<date>\d.*)$"
ss = ["description details #lo firstname lastname 2017-03-29", "description details #lo firstname lastname 2017 June 29"]
for s in ss:
    m = re.match(rx, s)
    if m:
        print(m.groupdict())

输出:

{'priority': 'lo', 'date': '2017-03-29', 'description': 'description details', 'name': 'firstname lastname'}
{'priority': 'lo', 'date': '2017 June 29', 'description': 'description details', 'name': 'firstname lastname'}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2020-11-29
    • 2011-11-28
    • 1970-01-01
    • 2019-03-16
    • 2015-04-23
    相关资源
    最近更新 更多