python re – regex for matching a pattern with an optional part

I need a regex pattern to find substrings of the form "a:" and an optional "b:" in a large string. The “a” string may be preceded and/or followed by arbitrary text, and I need to capture the two numbers.
I tried to make the “b” part optional by enclosing it in brackets, and placed a ".*" before and after the “a”-part to allow for the optional text:

>>> pat1 = re.compile(".*a:([0-9]*).*(b:([0-9]*\\.[0-9]*))*")
>>> pat2.match("prefix a:77 b:3.25").groups()
('77', None, None)

So this doesn’t because here the “.*” does not match the single space (why?). Then i tried

>>> pat2=re.compile(".*a:([0-9]*)[ .]*(b:([0-9]*\\.[0-9]*))*");
>>> pat2.match("prefix a:77 b:3.25").groups()
('77', 'b:3.25', '3.25')
>>> pat2.match("prefix a:77 something b:3.25").groups()
('77', None, None)
>>> pat2.match("prefix a:77 something").groups()   
('77', None, None)

Again not what i need, because here, while "[ .]*" matches the space " ", it does not match " something " (again, why?)

How would the pattern need to look so i can match it to strings like "something_optional a:43 something_optional b:345.7" and "something_optional a:43 something_optional"?

Read more here: Source link