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:
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)