Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing dash in string but not several consecutive dashes

Tags:

regex

php

This is a regex where string must start and end with an alphanumeric character and can contain alphanumeric characters and dashes.

/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-]+[a-zA-Z0-9]{1}$/

How can I make sure that the consecutive dashes are not allowed? for example:

should allow: some-string

should NOT allow: some--string

Thanks

Edit: I want to allow several dashes, just not consecutively. for example "some-thing-here" is OK, and "some--thing" is NOT.

like image 677
DavidW Avatar asked Nov 07 '25 02:11

DavidW


2 Answers

No need for complicated patterns with optional dashes just use this:

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

See it here on Regexr

Start with at least one alphanumeric. Then there can be a dash followed by at least one alphanumerics 0 ore more times.

like image 67
stema Avatar answered Nov 08 '25 21:11

stema


Something like:

/^[a-zA-Z0-9]{1}\-?([a-zA-Z0-9]+\-?)*[a-zA-Z0-9]{1}$/

The key part being \-?([a-zA-Z0-9]+\-?)* which makes it read "a letter/number, optional dash, any amount of (some letters/numbers, optionally followed by a dash), ending in a letter or number."

This allows some-string, my-double-dash-string but not my-double--dash-string.

like image 23
Joe Avatar answered Nov 08 '25 21:11

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!