Reputation: 637
I currently need to allow a "-" sign in this regular expression ^[a-zA-Z0-9]*$
.
Upvotes: 0
Views: 1299
Reputation: 4724
Hyphen can be included immediately after the open bracket [ or before the closing bracket ] in the character class. You should not include in the middle of the character class, otherwise it will treat as range characters and some Regex engine might not work also.
In your case both are valid solutions
(^[-a-zA-Z0-9]*$) - Starting of the Char class
(^[a-zA-Z0-9-]*$) - End of the Char class
Demo:
http://regex101.com/r/yP3sH7/2
Upvotes: 0
Reputation: 31045
You could use a regex like this:
^[a-z\d]+[-a-z\d]+[a-z\d]+$
The idea is to use insensitive flag to avoid having A-Za-z
and use only a-z
. And also use \d
that's the shortcut for 0-9
.
So, basically the regex is compound of three parts:
^[a-z\d]+ ---> Start with alphanumeric characters
[-a-z\d]+ ---> can continue with alphanumeric characters or dashes
[a-z\d]+$ ---> End with alphanumeric characters
Upvotes: 1
Reputation: 6438
Simply add it as the first character after the opening bracket: ^[-a-zA-Z0-9]*$
Or, to match one or more of letters/numbers with a dash in between: ^[a-zA-Z0-9]+-[a-zA-Z0-9]+$
Upvotes: 1