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.
source to share
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.
source to share
I would go with an alternative like this:
^([A-Za-z]|[A-Za-z][\w-]*[A-Za-z0-9])$
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 ( ^$
)
source to share