Find a decimal with a precision of 2 using yes pattern|no pattern

62 Views Asked by At

Can someone please point out the mistake I am making, why 123 is not matching here?

def is_decimal(num):
    import re
    pattern = re.compile(r"(\b\d+\.)(?(1)\d{1,2}\b|\d+)")
    result = pattern.search(num)
    return bool(result)


print(is_decimal('123.11'))
print(is_decimal('123'))
print(is_decimal('0.21'))

print(is_decimal('123.1214'))
print(is_decimal('e666.86'))

expected output: True, True, True, False, False

actual output : True, False, True, False, False

2

There are 2 best solutions below

0
Poe Dator On

try pattern = re.compile(r"(\b\d+\.*)(?(1)\d{1,2}\b|\d+)")

0
Ken T On

You may try the following pattern:

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

One of the key is to not use \b since the dot (.) is also considered as a word boundary which causes false parsing. Instead, you may use ^ to match the start of the string and $ the end of the string.

The above pattern can be tested interactively at the following website:

https://regex101.com/r/CixCHT/4