Regex Letters, Numbers, Dashes, and Underscores

Regex

Regex Problem Overview


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

Regex Solutions


Solution 1 - 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.

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

Solution 2 - Regex

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_-]+)

Solution 3 - Regex

Depending on your regex variant, you might be able to do simply this:

([\w-]+)

Also, you probably don't need the parentheses unless this is part of a larger expression.

Solution 4 - Regex

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGeorge JohnstonView Question on Stackoverflow
Solution 1 - RegexJohn KnoellerView Answer on Stackoverflow
Solution 2 - RegexwaxwingView Answer on Stackoverflow
Solution 3 - RegexMark ByersView Answer on Stackoverflow
Solution 4 - RegexMariusView Answer on Stackoverflow