【问题标题】:Regex starts with alphabet or underscore (_)正则表达式以字母或下划线 (_) 开头
【发布时间】:2020-08-29 19:32:51
【问题描述】:

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

预期的有效字符串:

  1. _姓名
  2. _name.First
  3. 名字优先
  4. 姓名
  5. 姓名.名字
  6. 名字优先
  7. 一个
  8. b

我尝试使用下面给定的正则表达式,但不适用于单个字母。

^[a-zA-Z0-9_][a-zA-Z0-9_|/.|/-]{1,20}[a-zA-Z0-9]$

【问题讨论】:

  • [\w-] 可能几乎是您想要的,但并不完全是您想要的(实际上是 Unicode 支持)

标签: regex


【解决方案1】:

使用

^[a-zA-Z0-9_](?:[a-zA-Z0-9_.-]{0,20}[a-zA-Z0-9])?$

proof

说明

                         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

【讨论】:

  • 它几乎适用于所有情况。我遇到了它正确验证起始字符串的位置,但如果长度为 2 的字符串不起作用。示例:1. _Test.name - 成功 2. test_name - 成功 3. test-name - 成功 4. _T - 失败
  • @EngMyWorld 将{1,20} 替换为{0,20}
猜你喜欢
  • 2010-09-25
  • 2016-01-14
  • 2014-10-16
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
相关资源
最近更新 更多