Skip to main content
 首页 » 编程设计

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

2025年05月04日24leader

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

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'