Simple regex question

Hi all, I have the following regular expression /[a-zA-Z0-9\-]/g

Basically, I am trying to make a pattern such that a string has ONLY alphabetical characters and/or a hyphen. The above regex matches strings if it has at least one character in the range, so it doesn’t really do what I want it to do. So let’s say, for example, I try to match the string “Test-String:Yay” with the above regex, it will match, but the regex that I’m trying to get shouldn’t match it because it has a colon, which is not among the permitted characters. Thank you for your time.

/[a-Za-z\-]*?/g

Wait, you don’t want to match digits.
Then it is

^([a-zA-Z-]+)$

Let me break this down

That ONLY right there indicates that the can be no other characters before what you want to match, an no characters after what you want to match. So you need ^ to indicate the start of the string and $ to indicate the end of the string.

That would be ([a-zA-Z0-9-]+)
Note that a dash doesn’t have to be escaped when you use it in a character class!

So the final regex is ^([a-zA-Z0-9-]+)$

:slight_smile:

That didn’t quite work. From what I understand about regex (which isn’t very much) is that the expression you provided looks to find at least one of the characters in the list (I’m not too sure about this). If I’m wrong, can you provide some explanation about the expression? Also, I’m trying to find an expression such that it doesn’t match with any string that contains characters not specified in the list (so in my case, only alphabetical, numerical, and hyphens are allowed).