Python regex: including a space within a range of characters

I have a regular expression that matches the alphabet, numbers, _ and - (with minimum and maximum length).

^[a-zA-Z0-9_-]{3,100}$ 

I want to include spaces in this character set.

According to the Python documentation:

Character classes such as \ w or \ S are also accepted within the set.

So I tried:

 ^[a-zA-Z0-9_-\s]{3,100}$ 

But this leads to an incorrect character range error. How to include a space in the above set?

+6
source share
3 answers

The problem is not in \s , but in - , which indicates a range of characters if it is not at the end or beginning of the class. Use this:

 ^[a-zA-Z0-9_\s-]{3,100}$ 
+18
source

^[-a-zA-Z0-9_\s]{3,100}

_-\s interpreted as a range. The symbol representing itself must be the first or last symbol within [...]

+2
source

You're on the right track, add a second backslash to avoid the slash, because the backslash is an escape character.

 ^[a-zA-Z0-9_\\-\\s]{3,100}$ 
0
source

All Articles