To disallow _
with \w
, you may use the opposite class \W
(non-word shorthand character class) in a negated character class and exclude a _
by adding it to the negated character class:
r'^[^\W_]+$'
^^^^
This pattern matches start of string (^
), one or more characters other than non-word chars (=matches all word chars) and other than _
(so, all that are \w
but excluding a _
), and then the end of string.
Or (if you only work with ASCII) just use
r'(?i)^[a-z0-9]+$'
As \w
= [a-zA-Z0-9_]
without the re.UNICODE
flag.
The (?i)^[a-z0-9]+$
matches both lower- and uppercase ASCII letters due to the case insensitive inline modifier (?i)
.