Search code examples
regexseleniumreplaceall

regex excluding time from text


I would like to extract time from the text below using regex.

Text: "Media: a few minutes ago, 3:25 pm uts"

Regex pattern to select only time (ex: 3:25) from the above text?


Solution

  • Use regex /\b[0-9]+:[0-9]+\b/. Explanation:

    • \b - word boundary
    • [0-9]+ - 1+ digits
    • : - literal colon
    • [0-9]+ - 1+ digits
    • \b - word boundary

    I do not know your specific use in selenium, but here is an example:

    src = 'Media: a few minutes ago, 3:25 pm uts'
    pattern = re.compile(r'(\\b[0-9]+:[0-9]+\\b)')
    match = pattern.search(src)
    print match.groups()[0]
    

    Output:

    3:25