代码之家  ›  专栏  ›  技术社区  ›  sberry

用于筛选不需要的用户名的正则表达式

  •  0
  • sberry  · 技术社区  · 14 年前

    在我工作的网站上,我有一个要求,用户名不能以 <alpha><alpha>_

    因此,这些不应被允许:

    • 苏酷小子
    • 我的小马

    • __苏酷小子
    • 没有人吗

    在我使用的框架中,我只能对匹配的正则表达式进行验证,而不能对不匹配的正则表达式进行验证。到目前为止,我想到了这个:

    "/^([^A-Za-z0-9]{2}\_|[A-Za-z0-9]{3,27})/"
    

    这适用于大多数物品,但在“苏酷盖”上失败。

    在此正则表达式上的任何帮助都将不胜感激。:)

    4 回复  |  直到 14 年前
        1
  •  2
  •   Mewp    14 年前

    你的正则表达式是 /^(?![a-zA-Z0-9]{2}_)/ {两个字母数字字符和一个下划线}”。

        2
  •  3
  •   Bob Fincheimer    14 年前

    negative lookahead :

    ^(?![A-Za-z]{2}_)[A-Za-z0-9_]{3,27}$

    我们来分解一下:

    Assert position at the beginning of a line (at beginning of the string or after a line break character) «^»
    Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?![A-Za-z]{2}_)»
       Match a single character present in the list below «[A-Za-z]{2}»
          Exactly 2 times «{2}»
          A character in the range between “A” and “Z” «A-Z»
          A character in the range between “a” and “z” «a-z»
       Match the character “_” literally «_»
    Match a single character present in the list below «[A-Za-z0-9_]{3,27}»
       Between 3 and 27 times, as many times as possible, giving back as needed (greedy) «{3,27}»
       A character in the range between “A” and “Z” «A-Z»
       A character in the range between “a” and “z” «a-z»
       A character in the range between “0” and “9” «0-9»
       The character “_” «_»
    Assert position at the end of a line (at the end of the string or before a line break character) «$»
    
        3
  •  1
  •   Emil Vikström    14 年前

    只是提出一个否定的论断,比如:

    /^([^A-Za-z0-9]{2}(?!\_)|[A-Za-z0-9]{3,27})/
                       ^^--Notice the assertion.
    

    下面是一个完整的测试用例:

    <?php
    $names = array('SU_Coolguy','MR_Nobody','my_Pony','__SU_Coolguy','MRS_Nobody','YourPony');
    
    foreach($names as $name){
            echo "$name => ";
            if(preg_match('/^([^A-Za-z0-9]{2}(?!\_)|[A-Za-z0-9]{3,27})/',$name)) {
                    echo 'ok';
            }else{
                    echo 'fail';
            }
            echo "\n";
    }
    ?>
    

    SU_Coolguy => fail
    MR_Nobody => fail
    my_Pony => fail
    __SU_Coolguy => ok
    MRS_Nobody => ok
    YourPony => ok
    
        4
  •  0
  •   JaakkoK    14 年前

    在这种情况下,一个简单的方法就是将其分为大小写:用户名要么以非alpha开头,要么以alpha和非alpha开头,要么以两个alpha和非下划线开头,大致如下:

    /^([^A-Za-z]|[A-Za-z][^A-Za-z]|[A-Za-z][A-Za-z][^_])/