Reputation: 19
I'm trying to check string starting with underscore(_) or alphabet and can contain only letters, digits, hyphens, underscores or periods. The string can also be of length 1.
Expected valid strings:
I tried using the below given regex but is not working for a single alphabet.
^[a-zA-Z0-9_][a-zA-Z0-9_|/.|/-]{1,20}[a-zA-Z0-9]$
Upvotes: 0
Views: 1556
Reputation: 18631
Use
^[a-zA-Z0-9_](?:[a-zA-Z0-9_.-]{0,20}[a-zA-Z0-9])?$
See proof.
Explanation
EXPLANATION
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[a-zA-Z0-9_] any character of: 'a' to 'z', 'A' to 'Z',
'0' to '9', '_'
--------------------------------------------------------------------------------
(?: group, but do not capture (optional
(matching the most amount possible)):
--------------------------------------------------------------------------------
[a-zA-Z0-9_.- any character of: 'a' to 'z', 'A' to
]{0,20} 'Z', '0' to '9', '_', '.', '-' (between
0 and 20 times (matching the most amount
possible))
--------------------------------------------------------------------------------
[a-zA-Z0-9] any character of: 'a' to 'z', 'A' to
'Z', '0' to '9'
--------------------------------------------------------------------------------
)? end of grouping
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
Upvotes: 1