Including a hyphen in a regex character bracket?

Solution 1:

Escaping using \- should be fine, but you can also try putting it at the beginning or the end of the character class. This should work for you:

/^[a-zA-Z0-9._-]+$/

Solution 2:

Escaping the hyphen using \- is the correct way.

I have verified that the expression /^[a-zA-Z0-9.\-_]+$/ does allow hyphens. You can also use the \w class to shorten it to /^[\w.\-]+$/.

(Putting the hyphen last in the expression actually causes it to not require escaping, as it then can't be part of a range, however you might still want to get into the habit of always escaping it.)

Solution 3:

The \- maybe wasn't working because you passed the whole stuff from the server with a string. If that's the case, you should at first escape the \ so the server side program can handle it too.

  • In a server side string: \\-
  • On the client side: \-
  • In regex (covers): -

Or you can simply put at the and of the [] brackets.