Reputation: 2034
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
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
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