Home > Mobile >  regex: getting all matches for group
regex: getting all matches for group

Time:12-13

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.

CodePudding user response:

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"\b\d{4,10}-\d{4,10}\b"

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

Prints:

0700-1300
1830-2230

CodePudding user response:

Try this regex.

(\d{4}-\d{4})

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

  • Related