Nitish Parkar
Nitish Parkar

Reputation: 2868

Python regex: Including whitespace inside character range

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

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

I want to include whitespace in that set of characters.

According to the Python documentation:

Character classes such as \w or \S are also accepted inside a set.

So I tried:

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

But it gives bad character range error. How can I include whitespace in the above set?

Upvotes: 7

Views: 11452

Answers (3)

David Lai
David Lai

Reputation: 822

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

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

Upvotes: -1

dda
dda

Reputation: 6203

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

_-\s was interpreted as a range. A dash representing itself has to be the first or last character inside [...]

Upvotes: 3

Martin Ender
Martin Ender

Reputation: 44259

The problem is not the \s but the - which indicates a character range, unless it is at the end or start of the class. Use this:

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

Upvotes: 25

Related Questions