python - 在正则表达式匹配中提取组

标签 python regex

我有一组输入。 我正在尝试编写一个正则表达式来匹配输入中的以下模式:

Day at Time on location

示例输入:

Today at 12:30 PM on Sam's living room

文本的粗体部分因输入而异。

我写了下面的正则表达式:

import regex as re

input_example = "Today at 12:30 PM on Rakesh's Echo"
regexp_1 = re.compile(r'(\w+) at (\d+):(\d+) (\w+) on (\w+)')
re_match = regexp_1.match(input_example)

哪个有效,我正在匹配正确的模式。我现在正试图从模式中提取组。

我想要的输出是:

re_match.group(1)
>> "Today"
re_match.group(2)
>> "12:30 PM"
re_match.group(3)
>> "Sam's living room"

但是,我当前的正则表达式匹配没有给我这个输出。给我上述输出的正确正则表达式是什么?

最佳答案

您可以创建嵌套组,但那样可读性会很差,因为您必须计算组的确切数量,然后您会忘记该数字的确切含义。

最好使用命名组。这是从 REPL 复制而来的:

>>> import re
... 
... input_example = "Today at 12:30 PM on Rakesh's Echo"
... regexp_1 = re.compile(r'(?P<day>\w+) at (?P<time>(\d+):(\d+) (\w+)) on (?P<place>\w+)')
... re_match = regexp_1.match(input_example)
>>> list(re_match.groups())
['Today', '12:30 PM', '12', '30', 'PM', 'Rakesh']
>>> re_match.group('day')
'Today'
>>> re_match.group('time')
'12:30 PM'
>>> re_match.group('place')
'Rakesh'

关于python - 在正则表达式匹配中提取组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49861405/

相关文章:

PHP exec() 命令不会使用 sendkeys 启动 python 脚本

python - 正则表达式 Python 模式

regex - vim 语法匹配错误([A-Z] 匹配所有字母字符)

javascript - 日期正则表达式

regex - sed 中的非贪婪(不情愿)正则表达式匹配?

python - 如何将具有字节值的字符串转换回字节?

python - 写操作部分完成

python - 在 Python 中重写实例方法内的函数

regex - AWK 匹配以数字开头的字符串

python - 正则表达式:不匹配已经是单词一部分的字符串