Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this 12 digit string fail to match regex "\b\d{12}\b"?

I am adding some code to validate that the incoming parameter is a stringified 12-digit integer.

My code::

id = event['id']# incoming parameter called 'id'
logger.info(f"Received id {id}.  Validating that it contains 12 digits...")
regex = "\b\d{12}\b"
if re.fullmatch(regex, id):
    logger.info(f"{id} is a 12 digit string")
    valid_param = True
else:
    logger.warn(f"{id} is not a 12 digit string")
    valid_param = False
return valid_param

When I run it I get:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Received id 123123123123.  Validating that it contains 12 digits...
id is not a 12 digit string

I’ve tried str(id) but got same result. I’ve used type(id) to confirm it is already a string.
I even tried int(id) for the fun of it (but got, not surprisingly expected string or bytes-like object).

What could be going on?

>Solution :

It’s because the regex is not defined as a raw string literal. You need to put a r before the quotes when defining the regex. The following code prints True:

import re
regex = r"\b\d{12}\b"
id = '123123123123'
if re.fullmatch(regex, id):
    print(True)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading