user989865
user989865

Reputation: 637

Regular expression to allow dash sign

I currently need to allow a "-" sign in this regular expression ^[a-zA-Z0-9]*$.

Upvotes: 0

Views: 1299

Answers (3)

Sivasakthi Jayaraman
Sivasakthi Jayaraman

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

Federico Piazza
Federico Piazza

Reputation: 31045

You could use a regex like this:

^[a-z\d]+[-a-z\d]+[a-z\d]+$

Working demo

enter image description here

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

rje
rje

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

Related Questions