Regex以字母表或下划线(_)开头



我正在尝试检查以下划线(_(或字母表开头的字符串,并且只能包含字母、数字、连字符、下划线或句点。字符串的长度也可以是1。

预期的有效字符串:

  1. _名称
  2. _name。第一
  3. 名字在前
  4. 名称
  5. name。第一
  6. 名字在前
  7. A
  8. 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

相关内容

最新更新