Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Letters, Numbers, Dashes, and Underscores

Tags:

regex

Im not sure how I can achieve this match expression. Currently I am using,

([A-Za-z0-9-]+) 

...which matches letters and numbers. I would also like to match on dashes and underscores in the same expression. Anyone know how?

I would like to be able to match product_name and product-name

like image 405
George Johnston Avatar asked Feb 25 '10 22:02

George Johnston


People also ask

Do you need to escape underscores in regex?

Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.

What is the regex for underscore?

The _ (underscore) character in the regular expression means that the zone name must have an underscore immediately following the alphanumeric string matched by the preceding brackets. The . (period) matches any character (a wildcard).

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

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.


2 Answers

Just escape the dashes to prevent them from being interpreted (I don't think underscore needs escaping, but it can't hurt). You don't say which regex you are using.

([A-Za-z0-9\-\_]+) 
like image 72
John Knoeller Avatar answered Sep 19 '22 13:09

John Knoeller


Your expression should already match dashes, because the final - will not be interpreted as a range operator (since the range has no end). To add underscores as well, try:

([A-Za-z0-9_-]+) 
like image 30
waxwing Avatar answered Sep 18 '22 13:09

waxwing