简体   繁体   中英

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.

With a given list of Strings

  • The Time is 12H 3M 12S
  • The Time is 3M 12S
  • It is 12H 3M
  • Ready in 12S
  • The Time is 6H

I would like to extract into 3 groups H, M and S, somehow like

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

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

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

Easyliy I could then access the H, M and S components by group(1-3). 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. Else this expression is optionally empty and matches everything, I guess.

Here's a link to the example: https://regex101.com/r/LKAKbx/5

How can I get the numbers only as groups from match, eg:

The Time is 12H 3M 12S

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

Or

Ready in 12S

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

Use a positive lookahead to make sure we have at least one of H , M or S .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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