1

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

1
  • What is your question? Commented Jan 3, 2020 at 16:27

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly what I was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.