我有一组输入。 我正在尝试编写一个正则表达式来匹配输入中的以下模式:
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/