【问题标题】:username regex alphanumeric with underscore only用户名正则表达式字母数字仅带下划线
【发布时间】:2014-01-31 15:38:30
【问题描述】:

我正在尝试为 php 的 preg_match 找到一个正则表达式,它允许字母数字字符带下划线,但下划线必须在字符之间(而不是字符串的开头或结尾),并且每个下划线旁边永远不能有 2 个下划线其他。

例子:

无效:

_name
na_me_
na__me

有效:

na_me
na_m_e

我发现的大部分内容都适用,但不能防止重复下划线是:

/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/

但就像我说的,这仍然允许像 na__me 这样的情况。

有人有什么想法吗?谢谢!

【问题讨论】:

  • 语言是什么?
  • @John McMullen 有什么不好?你的不允许na__me
  • 英文,抱歉没有指定@Jonny5,我希望它禁止 na__me.. 我列出的那个允许它(基本上,只找到 na_me,而不是 na__me)
  • @JohnMcMullen 当我测试你的时,它似乎不允许重复的下划线。请参阅regex101.com/r/bX4wW8 唯一匹配的是您显示标记为有效的那个
  • 奇怪,当我在第二台服务器以及 regex101 检查站点上再次尝试时,它工作正常...我想这都是为了 null...

标签: php regex preg-match


【解决方案1】:

这样就可以了:

(?x)           # enable comments and whitespace to make
               # it understandable.  always always do this.

^              # front anchor

[\pL\pN]       # an alphanumeric

# now begin a repeat group that 
# will go through the end of the string

(?: [\pL\pN]   # then either another alnum
  |            # or else an underbar surrounded
               # by an alnum to either side of it
    (?<= [\pL\pN] )      # must follow an alnum behind it
    _                    # the real underscore
    (?=  [\pL\pN] )      # and must precede an alnum before it
) *            # repeat that whole group 0 or more times

\z             # through the true end of the string

所以你从一个字母数字开始,然后在末尾有任意数量的字母数字,将任何实际的下划线限制为由实际的字母数字包围到任何一侧。

【讨论】:

    【解决方案2】:

    你的看起来不错。和这个一样,它有点短:

    /^[a-z](?:_?[a-z0-9])*$/i
    

    【讨论】:

    • @VahidAlvandi \. 匹配一个点。需要反斜杠,因为. 有特殊含义;没有反斜杠,它匹配 any 字符。在字符类中,. 失去了其特殊含义,因此不需要反斜杠。例如,[0-9.] 匹配一个数字或点。
    【解决方案3】:

    如果您希望 REGEX 处理特定长度的字符,请使用 {}

    例如

    [a-z]{2,4}

    将返回长度为 2、3 和 4 的所有小写字母字符串。

    在您的情况下,您将使用{0,1} 表示NO1 下划线是可以接受的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-25
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多