How to regex match a string of alnums and hyphens, but which doesn't begin or end with a hyphen?
- by Shahar Evron
I have some code validating a string of 1 to 32 characters, which may contain only alpha-numerics and hyphens ('-') but may not begin or end with a hyphen.
I'm using PCRE regular expressions & PHP (albeit the PHP part is not really important in this case).
Right now the pseudo-code looks like this:
if (match("/^[\p{L}0-9][\p{L}0-9-]{0,31}$/u", string)
and
not match("/-$/", string))
print "success!"
That is, I'm checking first that the string is of right contents, doesn't being with a '-' and is of the right length, and then I'm running another test to see that it doesn't end with a '-'.
Any suggestions on merging this into a single PCRE regular expression?
I've tried using look-ahead / look-behind assertions but couldn't get it to work.