Asynchronous
Asynchronous

Reputation: 3977

Regex to allow single hyphen and underscore but not at beginning or end of string

I have this Regex I modified to allow underscores, hyphen, letters and numbers. I am trying to modify it further so that it has the following properties:

  1. Allow only Numbers, Letters
  2. Allow Underscore or Hyphen anywhere between the first and last character
  3. Cannot start with underscore or hyphen (only between first and last character).

Here's what I have right now:

^[a-zA-Z0-9_-]*$

Upvotes: 3

Views: 6401

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

Try this:

^[a-zA-Z0-9](?:[a-zA-Z0-9_-]*[a-zA-Z0-9])?$

Or this, which will simply ensure that the string does not start with a hyphen or underscore:

^[a-zA-Z0-9][a-zA-Z0-9_-]*$

Upvotes: 9

Micha Wiedenmann
Micha Wiedenmann

Reputation: 20843

^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9])$

Either one of the three possibilities:

  • [a-zA-Z0-9]
  • [a-zA-Z0-9][a-zA-Z0-9]
  • [a-zA-Z0-9][a-zA-Z0-9_-]*[a-zA-Z0-9]

Upvotes: 2

Related Questions