Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preg-match for repeated characters

I need to validate a string that can have lower-case characters and dashes but not at the beginning nor the end nor repeated. Then can have numbers too, but not at the beginning.

This is how it should work:

Match: ab9cd-a9bc-abbbc95
Not match: 5abcd
Not match: abbcd-
Not match: -abcd
Not match: abcd--abcd

I have been able to do everything but the last case, where a repeated dash shouldn't match.

I have this:

/^[a-z]+[a-z0-9\-]+[a-z0-9]$/

And I tried this but didn't work as expected:

/^[a-z]+[a-z0-9\-?]+[a-z0-9]$/
like image 472
user2135040 Avatar asked Dec 12 '25 16:12

user2135040


1 Answers

Another way to do it:

^[a-z](?:[a-z\d]|[a-z\d]\-)*[a-z\d]+$

Explained demo here: http://regex101.com/r/mE8pB8

like image 87
CSᵠ Avatar answered Dec 15 '25 07:12

CSᵠ