aureylz
aureylz

Reputation: 25

Regex with letter number and dash without leading and trailing dash

Sorry if my question can be simple but, I'm blocked.

I was looking for a way to validate a regex that match several cases :

I've tried this : ^[a-zA-Z0-9]{1}(?:([a-zA-Z0-9][-]{0,1}){0,98}[a-zA-Z0-9])?$

It works for almost every cases. Except those 2 cases :

Can someone help me please ? Thanks a lot !

Upvotes: 0

Views: 310

Answers (2)

Armali
Armali

Reputation: 19375

Here's just an alternative to Jan's already perfect solution.

^(?:[^\W_]|(?<=[^\W_])-(?=[^\W_])){1,100}$

It can be "decrypted" as: between 1 and 100 occurrences of either

  • a letter or digit, or
  • a dash preceded and followed by a letter or digit.

Upvotes: 1

Jan
Jan

Reputation: 43169

You are looking for lookaheads and another character class:

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

See a demo on regex101.com.

Upvotes: 2

Related Questions