Regex doesn't work in front end

https://anvil.works/ide#clone:DAA6HQZGOBEOW5FO=BZWJEUOLYIA3AVJLXRTHU2ZT

I’m going to guess it’s a known limitation but I don’t see a mention of it. I have a few lines of code that do work in Python locally but when I deploy to Anvil, it gives me a TypeError even though it is the correct type. (TypeError: pattern must be a string)

import re
my_id = 12346578
re_not_digit = re.compile("\D")
my_id_str = str(my_id)
print(type(my_id_str))
not_digit_result = re.findall(re_not_digit, my_id_str)
print(len(not_digit_result), not_digit_result)

I don’t know much about python regex, I’m afraid. But if I do this it seems to work :

not_digit_result = re.findall("\D", my_id_str)

Not sure if that’s what you’re looking for, though.
I tested it by doing this :

my_id_str = str(my_id)+"G"

and it found the not-digit correctly.

Try with '\\D' or with r'\D'

I just ran into this bug.

It seems that re.compile gets transformed into an object in the front end, and doesn’t seem to work properly.

But, if I provide the regex pattern as a string, then things work.

For instance, I am trying to write a form validator for email strings.

This works:

import re
cmpt = AddUserComponent()
EMAIL_REGEX = "(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)"
if re.match(EMAIL_REGEX, cmpt.text_box_email.text):
  # do something if invalid email string

But this fails.

import re
cmpt = AddUserComponent()
EMAIL_REGEX = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
if EMAIL_REGEX.match(cmpt.text_box_email.text):
  # do something if invalid email string

Hope this helps others.

Cheers. A.

1 Like

Welcome @andersgs,

I may be misinterpreting your post, but are you trying to write code to validate user input in form to ensure it is a valid email format?
If so, could you use the built in functionality Anvil has to change the ‘type’ of your TextBox to ‘email’. This is found in the Properties under Place Holder. See image below.

You could then use the Validator as described in the Form Validation Article
image

2 Likes

Doh! Thank you @rickhurlbatt. I completely missed that article.

1 Like