How to regex match a string of alnums and hyphens, but which doesn't begin or end with a hyphen?

Posted by Shahar Evron on Stack Overflow See other posts from Stack Overflow or by Shahar Evron
Published on 2010-04-23T17:11:59Z Indexed on 2010/04/23 17:13 UTC
Read the original article Hit count: 289

Filed under:
|
|
|
|

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.

© Stack Overflow or respective owner

Related posts about regex

Related posts about pcre