Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow - (dash) in regular expression

Tags:

regex

asp.net

I have the following regular expression but I want the text box to allow the dash character

^[0-9a-zA-Z \/_?:.,\s]+$ 

Anyone know how I can do this?

like image 674
Gavin Crawley Avatar asked Jan 12 '12 11:01

Gavin Crawley


People also ask

How do you include a dash in regex?

The quantifier notations 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.

What does '$' mean in regex?

Literal Characters and Sequences For instance, you might need to search for a dollar sign ("$") as part of a price list, or in a computer program as part of a variable name. Since the dollar sign is a metacharacter which means "end of line" in regex, you must escape it with a backslash to use it literally.

How do you add a hyphen to a regular expression in Java?

Inside character class - denotes range. e.g. 0-9 . If you want to include - , write it in beginning or ending of character class like [-0-9] or [0-9-] . You also don't need to escape .

What is difference [] and () in regex?

This answer is not useful. Show activity on this post. [] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.


1 Answers

The dash needs to be the first/last character in the character class in order to be used literally:

^[-0-9a-zA-Z \/_?:.,\s]+$  ^[0-9a-zA-Z \/_?:.,\s-]+$ 

You could also escape it, if not the first/last:

^[0-9a-zA-Z\- \/_?:.,\s]+$ 
like image 124
Oded Avatar answered Sep 22 '22 01:09

Oded