Mathachew
Mathachew

Reputation: 2034

Regular expression with letters, numbers and dashes, but with no leading or trailing dash

In my ASP.NET MVC project is a regular expression for validating a string with alphanumeric characters and dashes, while also not allowing leading or trailing dashes:

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

This works for most use cases:

safename                (valid)
123                     (valid)
there-is-something-here (valid)
your-name-goes-here     (valid)
-something-is-up        (invalid)
say-what-               (invalid)

However, there are some use cases that I want to be valid, but are not:

a-b                     (valid)
a-bc-d                  (valid)
ab-cd-e                 (valid)
a-bc-de                 (valid)
this-is-a-test          (invalid)
a-b-c                   (invalid)
1-2-3                   (invalid)

I can have a single leading and/or trailing character, but not a single character within the rest of the string. I want a-b-c or 1-2-3 to be valid, but any modifications I've tried haven't yielded the desired results. I made a minor change to the first and third groups, but leading and trailing dashes pass:

^(([a-zA-Z0-9]{0,}?)(\-{0,}?)([a-zA-Z0-9]{0,}?))+$

I've reached my limit on regular expressions and would appreciate any guidance. Is the result I'm looking for possible with a single expression?

Upvotes: 2

Views: 1833

Answers (3)

Jerry
Jerry

Reputation: 71538

You might use something like this:

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

If you want to allow only a single dash between each alphanumeric chars. Otherwise, turn the - to -+ for multiple dashes.

Upvotes: 2

huembert
huembert

Reputation: 49

I tried all your use cases with that expression:

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

1-2-3 is valid; 1-2- is not valid

Upvotes: 2

asontu
asontu

Reputation: 4659

This is what I would do, also prevents multiple dashes:

^(\w|(?<=\w)-(?=\w))+$

Tested here.

Upvotes: 1

Related Questions