【问题标题】:RegExp ignore special and repeated characters (username test)RegExp 忽略特殊字符和重复字符(用户名测试)
【发布时间】:2015-08-12 19:20:20
【问题描述】:

所有, 我正在尝试构造一个正则表达式(我将用于测试有效的用户名):

^[(0-9)|(_|\.)]|^[0-9]+$|[^a-zA-z0-9_.]{3,}|(_\.|\._)|\.{2,}|_{2,}

并针对此字符串对其进行测试:

1123@sssssasdf sslkdf*.sf...____.__sfsfdddddsss

这个正则表达式应该测试的是:

  1. 字符串不应以数字、下划线或点开头
  2. 字符串应该是字母数字
  3. 不应包含重复三次或更多次的字符——这会失败
  4. 不得同时包含下划线和点
  5. 不应同时包含点和下划线
  6. 不应包含重复的点不应包含重复的下划线

看起来所有案例都匹配但第 3 个。它不会捕获重复三次或更多次的重复字符。

我的问题是:

  1. 如何修复这个正则表达式,以便它可以捕获重复的字符?
  2. 如何优化这个正则表达式?

提前致谢

编辑 根据要求,有效字符串是:

  1. 约翰
  2. john.snow
  3. john.snow123
  4. john1.snow1
  5. john_snow
  6. john_snow123
  7. john1_snow1

无效的字符串是:

  1. 123
  2. 1john.snow
  3. .john_snow
  4. john__snow
  5. 约翰..雪
  6. jjjohn.snow
  7. _john_snow

【问题讨论】:

    标签: regex


    【解决方案1】:

    而且也可以这样做——

    (?i)^(?=[a-z])(?!.*?(?:\._|_\.|\.{2}|_{2}|([a-z\d])\1{2}))[a-z\d._]+$

    Formatted:

     (?i)                # Case insensitive
     ^                   # BOS
     (?= [a-z] )         # First char alpha
     (?!                 # Not these
          .*? 
          (?:
               \._                 # dot, underscore
            |  _\.                 # underscore, dot
            |  \.{2}               # 2 or more dots
            |  _{2}                # 3 or more underscore
            |  ( [a-z\d] )         # (1), 3 or more repeated alpha-num's
               \1{2} 
          )
     )
     [a-z\d._]+          # Get valid char's: alpha-num, dot and underscore
     $                   # EOS
    

    【讨论】:

      【解决方案2】:
      ^(?![0-9_.])(?!.*([._])\1)(?!.*(?:_\.|\._))(?!.*(.)\2{2,})[\w.]+$
      

      您可以为每个条件添加negative lookahead。参见演示。

      https://regex101.com/r/rO0yD8/6

      【讨论】:

        猜你喜欢
        • 2011-08-02
        • 2013-12-11
        • 2023-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多