Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including a hyphen in a regex character bracket?

$.validator.addMethod('AZ09_', function (value) {      return /^[a-zA-Z0-9.-_]+$/.test(value);  }, 'Only letters, numbers, and _-. are allowed'); 

When I use somehting like test-123 it still triggers as if the hyphen is invalid. I tried \- and --

like image 302
ParoX Avatar asked Sep 13 '10 00:09

ParoX


People also ask

How do you include a hyphen in regex?

In regular expressions, the hyphen ("-") notation has special meaning; it indicates a range that would match any number from 0 to 9. As a result, you must escape the "-" character with a forward slash ("\") when matching the literal hyphens in a social security number.

Do we need to escape hyphen in regex?

You only need to escape the dash character if it could otherwise be interpreted as a range indicator (which can be the case inside a character class).

What do the [] brackets mean in regular expressions?

By placing part of a regular expression inside round brackets or parentheses, you can group that part of the regular expression together. This allows you to apply a quantifier to the entire group or to restrict alternation to part of the regex. Only parentheses can be used for grouping.

How do you denote special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

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._-]+$/ 
like image 119
Mark Byers Avatar answered Nov 01 '22 17:11

Mark Byers