Python regex not greedy enough, multiple groups
Question: When trying to do some regexp matching in python, I stumbled over an oddity. I
wanted to match decimal numbers on the form xxx.yyy and divide them into three
groups for further processing. I ran something like the following snippet.

    
    
    #!/usr/bin/env python3
    
    import re
    
    matches = re.search("a=(\d+)(\.?)(\d+?)", "var k = 2;var a; a=46")
    print(matches.group(1))
    

Print returns 4, whereas 46 would be the expected result. Why would that be?
Python documentation states that the regexp + and * are greedy, but that does
not seem to be the case here. The reason seems to be that the last digit ends
up in the last group. I need to at least match the first and the last group. I
could skip the middle group if i use the last to distinguish between decimal
and non-decimal numbers.

It does however seem to work if the number matched is a decimal.

    
    
    #!/usr/bin/env python3
    
    import re
    
    matches = re.search("a=(\d+)(\.?)(\d+?)", "var k = 2;var a; a=46.3")
    print(matches.group(1))
    

Prints 46. I would be delighted if you could help me solve this conundrum.
Thank you.


Answer: It should be

    
    
    matches = re.search("a=(\d+(?:\.\d+)?)", "var k = 2;var a; a=46")
    

**[Ideone Demo](http://ideone.com/n8PARJ)**

**Reason**

Your regex is

    
    
    (\d+)(\.?)(\d+?)
    

Your `.` is optional which means that your both `.` and the next `\d+?` are
independent of each other.It means that it first matches all the digits (i.e.
till `4` in your example) of your input till the next `.` which is optional
and it requires at least one digit for the last group to succeed. So `6` will
be in last captured group.

This picture will make more clear

[![enter image description
here](http://i.stack.imgur.com/I6nRx.png)](http://i.stack.imgur.com/I6nRx.png)

