NoSenseEtAl
NoSenseEtAl

Reputation: 30028

How to get a capture group that doesnt always exist?

I have a regex something like

(\d\d\d)(\d\d\d)(\.\d\d){0,1}

when it matches I can easily get first two groups, but how do I check if third occurred 0 or 1 times.

Also another minor question: in the (\.\d\d) I only care about \d\d part, any other way to tell regex that \.\d\d needs to appear 0 or 1 times, but that I want to capture only \d\d part ?

This was based on a problem of parsing a

hhmmss

string that has optional decimal part for seconds( so it becomes

hhmmss.ss

)... I put \d\d\d in the question so it is clear about what \d\d Im talking about.

Upvotes: 19

Views: 20838

Answers (1)

stalk
stalk

Reputation: 12054

import re

value = "123456.33"

regex = re.search("^(\d\d\d)(\d\d\d)(?:\.(\d\d)){0,1}$", value)

if regex:
    print regex.group(1)
    print regex.group(2)
    if regex.group(3) is not None:
        print regex.group(3)
    else:
        print "3rd group not found"
else:
    print "value don't match regex"

Upvotes: 20

Related Questions