Nips
Nips

Reputation: 13890

How to validate unicode "word characters" in Python regex?

I have form with field:

name = forms.RegexField(regex=r'\w+$', label=u'Name', required=True)

but if I type special chars (ś for example) form not pass is_valid() function. How to do it?

Upvotes: 5

Views: 2009

Answers (2)

Benjamin Wohlwend
Benjamin Wohlwend

Reputation: 31898

Instead of defining the regex as a string, you can compile it to a regex object first, setting the re.U flag:

import re

name_regex = re.compile(r'\w+$', re.U)
name = forms.RegexField(regex=name_regex, label=u'Name', required=True)

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799580

Activate Unicode matching for \w.

name = forms.RegexField(regex=r'(?u)\w+$', label=u'Name', required=True)

Upvotes: 5

Related Questions