Search code examples
pythonregexmatchhierarchical

regex: Only match a hierarchical number in python when the whole number is correct


in python 2.7 i want to match a hierachical number only when the whole number is correct.

my_str1 = "10.2.15"
my_str2 = "10..2.15"
my_str3 = "10.2..15"

My regex is:

pattern = re.compile(r"^\d+\.?\d+\.?\d+")

This matches my_str1 and my_str3 (but not the whole one).

As in my_str2 i want no match for my_str3. What do i have to change in the regex?

Thank you.


Solution

  • You need to also use an end of string anchor $ that will force the match from the start (^) to the end of string.

    ^\d+\.?\d+\.?\d+$
                    ^
    

    See demo

    If you need to allow optional . + digits sequences, use this version with grouping and a limiting quantifier:

    ^\d+(?:\.?\d+){0,2}$
         ^       ^^^^^^
    

    You can adjust the min/max values as needed.

    See another demo