2

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

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173

2 Answers2

0

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

Poe Dator
  • 4,535
  • 2
  • 14
  • 35
0

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

Ken T
  • 2,255
  • 1
  • 23
  • 30