我正在尝试检查以下划线(_(或字母表开头的字符串,并且只能包含字母、数字、连字符、下划线或句点。字符串的长度也可以是1。
预期的有效字符串:
- _名称
- _name。第一
- 名字在前
- 名称
- name。第一
- 名字在前
- A
- b
我尝试使用下面给定的regex,但不适用于单个字母表。
^[a-zA-Z0-9_][a-zA-Z0-9_|/.|/-]{1,20}[a-zA-Z0-9]$
使用
^[a-zA-Z0-9_](?:[a-zA-Z0-9_.-]{0,20}[a-zA-Z0-9])?$
见证明。
解释
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