David
David

Reputation: 1245

Regex matching alphanumerics with possible dash in middle only

I have managed to get this far:

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

but the above expression doesn't limit length as I need it to. I need the pattern to only match 5-6 characters total. So, this is how it ought to work out:

safety        (valid)
safet-        (invalid)
s-a-fe        (valid)
-safet        (invalid)
s7-45         (valid)
s--fs         (invalid)

Consecutive hyphens are invalid. Leading and trailing hyphens are invalid. Overall length, which includes any hyphens, should be 5-6 characters. I've tried replacing my +s with ranges ({5,6}), but no luck. I appreciate any help.


Another route I tried was:

^[A-Z0-9][A-Z0-9-]{3,4}[A-Z0-9]$i

which seems good and efficient, but it allows for consecutive hyphens.

Upvotes: 3

Views: 2024

Answers (3)

Manoj Malakar
Manoj Malakar

Reputation: 1

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

Try this Demo: https://regex101.com/r/hc9mDO/1

Upvotes: 0

vks
vks

Reputation: 67968

(?!^-)(?!.*?-$)(?!.*?--)^[a-zA-Z0-9-]{5,6}$

Try this.See demo.

http://regex101.com/r/kM7rT8/15

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174696

Use a lookahead at the first to specify the number of characters going to be allowed.

^(?=.{5,6}$)[a-zA-Z0-9]+(?:-[a-zA-Z0-9]+)*$

DEMO

Upvotes: 3

Related Questions