Reputation: 1417
The starting and the end letter of the string should be in the interval [a-z0-9]. What's in the middle should be in the same interval [a-z0-9], plus the hyphen(-) character.
My regex pattern is:
/^[a-z0-9].*?[a-z0-9-][a-z0-9]$/
It seems to work fine, except for the fact that it doesn't validate a string containing only one valid character. For example, the string 'a'
.
Upvotes: 1
Views: 89
Reputation: 1642
As I understand it, you're looking for any string that consists of entirely lowercase alpha-numeric characters and hyphens, and where the first and last characters must not be a hyphen.
I've modified your RegEx so that it accepts any number of characters, but I'm not sure if that's what you're looking for, or if it's the easiest way. In order to strictly match what you've described, I had to remove part of your original pattern to get:
^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$
Upvotes: 2
Reputation: 2428
If I understand correctly, you want a RegExp that can match any of these scenarios
aabc-defg
abc
a-abc
abc-a
a
z0123abc-def4567y
Here's what I got ^[\w\d]*[\-]?[\w\d]*$
Working example: http://regexr.com/3gh4o
EDIT:
This was a suggested edit: /^[0-9a-z]*[-]?[0-9a-z]*$/
, could also work.
Upvotes: 2