简体   繁体   English

带有可选组的 Python 正则表达式,至少匹配一个

[英]Python regex with optional Groups, one match at least

So I thought I could just quickly do a re.match() with my given String, but I'm stuck.所以我想我可以用我给定的字符串快速地做一个 re.match() ,但我被卡住了。

With a given list of Strings使用给定的字符串列表

  • The Time is 12H 3M 12S时间是12H 3M 12S
  • The Time is 3M 12S时间是3M 12S
  • It is 12H 3M 12H 3M
  • Ready in 12S 12 秒内准备就绪
  • The Time is 6H时间是6H

I would like to extract into 3 groups H, M and S, somehow like我想提取到 3 组 H、M 和 S,不知何故

(?: (\\d{1,2})H)? (?: (\\d{1,2})H)?

(?: (\\d{1,2})M)? (?: (\\d{1,2})M)?

(?: (\\d{1,2})S)? (?: (\\d{1,2})S)?

Easyliy I could then access the H, M and S components by group(1-3).然后我可以轻松地按组(1-3)访问 H、M 和 S 组件。 I just would like to restrict the match to fulfill the creteria, that at least one of the optionl groups has to be triggered or it's no match.我只是想限制匹配以实现 creteria,至少必须触发一个 optionl 组,否则它不匹配。 Else this expression is optionally empty and matches everything, I guess.否则,我猜这个表达式可以选择为空并匹配所有内容。

Here's a link to the example: https://regex101.com/r/LKAKbx/5这是示例的链接: https : //regex101.com/r/LKAKbx/5

How can I get the numbers only as groups from match, eg:我怎样才能从比赛中以组的形式获取数字,例如:

The Time is 12H 3M 12S时间是12H 3M 12S

group(1) = 12, group(2) = 3, group(3) = 12组(1)= 12,组(2)= 3,组(3)= 12

Or或者

Ready in 12S 12 秒内准备就绪

group(1) = None, group(2) = None, group(3) = 12组(1) = 无,组(2) = 无,组(3) = 12

Use a positive lookahead to make sure we have at least one of H , M or S .使用积极的前瞻来确保我们至少有HMS

import re

strings = [
    'The Time is 12H 3M 12S',
    'The Time is 3M 12S',
    'It is 12H 3M',
    'Ready in 12S',
    'The Time is 6H',
]

for s in strings:
    res = re.search(r'(?= \d{1,2}[HMS])(?: (\d{1,2})H)?(?: (\d{1,2})M)?(?: (\d{1,2})S)?', s)
    #          here __^^^^^^^^^^^^^^^^^
    print(res.groups())

Output:输出:

('12', '3', '12')
(None, '3', '12')
('12', '3', None)
(None, None, '12')
('6', None, None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM