The regex starts and ends with different conditions, but allows a single character

So, I am stuck with the correct rule of this regex ... Here are the rules:

  • It must start with a letter.
  • It can ONLY contain letters, numbers, hyphens and underscores.
  • It must end with a letter or number.

I've come this far:

/\A^[A-Z]+[A-Z0-9\-_]*[A-Z0-9]$\z/i

      

Seems to work, but doesn't allow any letters. Therefore it a

will return false.

+3


source to share


3 answers


You can use this lookahead based regex instead of allowing single character input :

/^(?=.*?[A-Z0-9]$)[A-Z][\w-]*$/mgi

      



Demo version of RegEx

(?=.*?[A-Z0-9]$)

will enforce the rule that the string ends with a letter or number.

+2


source


Your regex expects at least two letters due to [A-Z]+

and [A-Z0-9]$

..

Use the following:

\A^[A-Z](?:[A-Z0-9\-_]*[A-Z0-9])?$\z
        ^^^                     ^

      



See DEMO

Explanation:

  • +

    not required as it is covered [A-Z0-9\-_]*

  • included the remaining pattern as optional (c ?

    ) for one character, but required for more than one.
+2


source


I would go with an alternative like this:

^([A-Za-z]|[A-Za-z][\w-]*[A-Za-z0-9])$

      

Demo here

The first alternative is a single letter, the second is a letter followed by a letter or number, or a hyphen 0 until indefinitely and ending with a letter or number. The parentheses form a capturing group and provide an alternative between the start and end of the line ( ^$

)

+1


source







All Articles