简体   繁体   中英

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.

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

^(?!.*\.\.)[\d.]+$

You can also use lookahead to negate matches where .. occur.See demo.

https://regex101.com/r/vV1wW6/29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM