How does a regex match a string of alnums and hyphens, but that doesn't start or end with a hyphen?

I have some code that checks for a 1 to 32 character string that can only contain alpha numeric and hyphens ('-'), but may not start or end with a hyphen.

I use PCRE and PHP regexes (although the PHP part is not very important in this case).

Currently, the pseudocode 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 first check that the string has the correct content, has no "-" value, and is of the correct length, and then I run another test to make sure it does not end with a '-' character.

Any suggestions for combining this into one PCRE regex?

I've tried using look-ahead / look-behind assertions but couldn't get it to work.

+2


a source to share


2 answers


Try this regex:

/^[\p{L}0-9](?:[\p{L}0-9-]{0,30}[\p{L}0-9])?$/u

      



And if you want to use look-around assertions:

/^[\p{L}0-9][\p{L}0-9-]{0,31}$(?<!-)/u

      

+2


a source


A slightly alternative approach would be to keep your generic class in one part and be specific about the points where you don't want hyphenation allowed.

/^(?!-)[\p{L}0-9-]{1,32}(?<!-)$/Du

      



Also note the modifier D

that everyone always forgets.

Finally, to be sure, you know you \pL

will fit a lot more than a-zA-Z

that, right? Just checking.

+1


a source







All Articles