regex: getting all matches for group

Question:

in python, i’m trying to extract all time-ranges (of the form HHmmss-HHmmss) from a string. i’m using this python code.

text = "random text 0700-1300 random text 1830-2230 random 1231 text"
regex = "(.*(d{4,10}-d{4,10}))*.*"
match = re.search(regex, text)

this only returns 1830-2230 but i’d like to get 0700-1300 and 1830-2230. in my application there may be zero or any number of time-ranges (within reason) in the text string. i’d appreciate any hints.

Asked By: 4mla1fn

||

Answers:

Try this regex.

(d{4}-d{4})

All you need is pattern {four digts}minus{ four digits}. Other parts are not needed.

Answered By: Aidis

Try to use re.findall to find all matches (Regex demo.):

import re

text = "random text 0700-1300 random text 1830-2230 random 1231 text"
pat = r"bd{4,10}-d{4,10}b"

for m in re.findall(pat, text):
    print(m)

Prints:

0700-1300
1830-2230
Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.