简体   繁体   English

Java中用户名的正则表达式(RegEx)

[英]Regular Expression (RegEx) for User Name in Java

How to form the RegEx of user name string in Java?如何在Java中形成用户名字符串的RegEx?

Rules in Exercise :练习规则:

  1. Only 3 - 10 characters.只有 3 - 10 个字符。
  2. Only 'a'-'z', 'A'-'Z', '1'-'9', '_' and '.'只有'a'-'z'、'A'-'Z'、'1'-'9'、'_'和'.' are allowed.被允许。
  3. '_' and '.' '_' 和 '。' can only be appeared 0 to 2 times.只能出现0到2次。
  • "abc_._" = false "abc_._" =假
  • "abc..." = false "abc..." = 假
  • "abc__" = true "abc__" = 真
  • "abc.." = true "abc.." = 真
  • "abc_." = true = 真

If I do not use Regex, it will be easier.如果我不使用正则表达式,它会更容易。


Without considering '1'-'9', I have tried the following RegEx but they are not workable.在不考虑“1”-“9”的情况下,我尝试了以下正则表达式,但它们不起作用。

String username_regex = "[a-zA-Z||[_||.]{0,2}]{3,10}";
String username_regex = "[a-zA-Z]{3,10}||[_||.]{0,2}";

My function :我的功能:

public static boolean isUserNameCorrect(String user_name) {
    String username_regex = "[a-zA-Z||[_]{0,2}]{3,10}";
    boolean isMatch = user_name.matches(username_regex);
    return isMatch;
}

What RegEx should I use?我应该使用什么正则表达式?

If I remember well from CS classes, it is not possible to create one single regex to satisfy all three requirements.如果我从CS类记得很清楚,这是不可能创建一个单一的正则表达式来满足所有这些要求。 So, I would make separate checks for each condintion.因此,我会对每个条件进行单独检查。 For example, this regex checks for conditions 1 and 2, and condition 3 is checked separately.例如,此正则表达式检查条件 1 和 2,而单独检查条件 3。

private static final Pattern usernameRegex = Pattern.compile("[a-zA-Z1-9._]{3,10}");

public static boolean isUserNameCorrect(String userName) {
    boolean isMatch = usernameRegex.matcher(userName).matches();
    return isMatch && countChar(userName, '.')<=2  && countChar(userName, '_') <=2;
}

public static int countChar(String s, char c) {
    int count = 0;
    int index = s.indexOf(c, 0);
    while ( index >= 0 ) {
        count++;
        index = s.indexOf(c, index+1);
    }
    return count;
}

BTW, notice the pattern that allows you to reuse a regex in Java (performace gain, because it is expensive to compile a regex).顺便说一句,请注意允许您在 Java 中重用正则表达式的模式(性能增益,因为编译正则表达式的成本很高)。

The reason that a regex cannot do what you want (again if I remember well) is that this problem requires a context-free-grammar, while regex is a regular grammar.正则表达式不能做你想做的事情的原因(如果我没记错的话)是这个问题需要上下文无关语法,而正则表达式是常规语法。 Ream more 铰更多

First off, ||首先, || isn't necessary for this problem, and in fact doesn't do what you think it does.不是这个问题所必需的,实际上并没有做你认为的那样。 I've only ever seen it used in groups for regex (like if you want to match Hello or World , you'd match (Hello|World) or (?:Hello|World) , and in those cases you only use a single | .我只见过它成组用于正则表达式(比如如果你想匹配HelloWorld ,你会匹配(Hello|World)(?:Hello|World) ,在这些情况下你只使用一个|


Next, let me explain why each of the regex you have tried won't work.接下来,让我解释为什么您尝试过的每个正则表达式都不起作用。

String username_regex = "[a-zA-Z||[_||.]{0,2}]{3,10}";

Range operators inside a character class aren't interpreted as range operators, and instead will just represent the literals that make up the range operators.字符类中的范围运算符不会被解释为范围运算符,而只会表示构成范围运算符的文字。 In addition, nested character classes are simply combined.此外,嵌套的字符类只是简单地组合在一起。 So this is effectively equal to:所以这实际上等于:

String username_regex = "[a-zA-Z_|.{0,2}]{3,10}";

So it'll match some combination of 3-10 of the following: a - z , A - Z , 0 , 2 , { , } , .所以它将匹配以下 3-10 个的组合: a - z , A - Z , 0 , 2 , { , } , . , | , | , and _ . , 和_

And that's not what you wanted.这不是你想要的。


String username_regex = "[a-zA-Z]{3,10}||[_||.]{0,2}";

This will match 3 to 10 of a - z or A - Z , followed by two pipes, followed by _ , |这将匹配 3 到 10 个a - zA - Z ,然后是两个管道,然后是_| , or . ,或. 0 to 2 times. 0~2次。 Also not what you wanted.也不是你想要的。


The easy way to do this is by splitting the requirements into two sections and creating two regex strings based off of those:做到这一点的简单方法是将需求分成两部分并基于这些创建两个正则表达式字符串:

  1. Only 3 - 10 characters, where only 'a'-'z', 'A'-'Z', '1'-'9', '_' and '.'只有 3 - 10 个字符,其中只有 'a'-'z'、'A'-'Z'、'1'-'9'、'_' 和 '.' are allowed.被允许。
  2. '_' and '.' '_' 和 '。' can only appear 0 to 2 times.只能出现0到2次。

The first requirement is quite simple: we just need to create a character class including all valid characters and place limits on how many of those can appear:第一个要求非常简单:我们只需要创建一个包含所有有效字符的字符类,并对可以出现的字符数进行限制:

"[a-zA-Z1-9_.]{3,10}"

Then I would validate that '_' and '.'然后我会验证 '_' 和 '.' appear 0 to 2 times:出现0到2次:

".*[._].*[._].*"

or或者

"(?:.*[._].*){0,2}" // Might work, might not. Preferable to above regex if easy configuration is necessary. Might need reluctant quantifiers...

I'm unfortunately not experienced enough to figure out what a single regex would look like... But these are at least quite readable.不幸的是,我没有足够的经验来弄清楚单个正则表达式的样子......但这些至少是相当可读的。

Please try this: [[aZ][0-9] [._]?[[aZ][0-9] [._]?[[aZ][0-9]*请试试这个:[[aZ][0-9] [._]?[[aZ][0-9] [._]?[[aZ][0-9]*

Niko尼可

EDIT : You're right.编辑:你是对的。 Then several Regexp : Regex1: ^[\\w.]{3-10}$ Regex2: ^[[aZ][0-9]] [_.]?[[aZ][0-9]] [_.]?[[aZ][0-9]]*$然后几个正则表达式: Regex1: ^[\\w.]{3-10}$ Regex2: ^[[aZ][0-9]] [_.]?[[aZ][0-9]] [_.] ?[[aZ][0-9]]*$

I hope I forgot nothing!我希望我什么都没忘记!

May not be elegant but you may try this:可能不优雅,但你可以试试这个:

^(([A-Za-z0-9\._])(?!.*[\._].*[\._].*[\._])){3,10}$

Here is the explanation:这是解释:

NODE                     EXPLANATION
--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1 (between 3 and 10
                           times (matching the most amount
                           possible)):
--------------------------------------------------------------------------------
    (                        group and capture to \2:
--------------------------------------------------------------------------------
      [A-Za-z0-9\._]           any character of: 'A' to 'Z', 'a' to
                               'z', '0' to '9', '\.', '_'
--------------------------------------------------------------------------------
    )                        end of \2
--------------------------------------------------------------------------------
    (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
      .*                       any character except \n (0 or more
                               times (matching the most amount
                               possible))
--------------------------------------------------------------------------------
      [\._]                    any character of: '\.', '_'
--------------------------------------------------------------------------------
      .*                       any character except \n (0 or more
                               times (matching the most amount
                               possible))
--------------------------------------------------------------------------------
      [\._]                    any character of: '\.', '_'
--------------------------------------------------------------------------------
      .*                       any character except \n (0 or more
                               times (matching the most amount
                               possible))
--------------------------------------------------------------------------------
      [\._]                    any character of: '\.', '_'
--------------------------------------------------------------------------------
    )                        end of look-ahead
--------------------------------------------------------------------------------
  ){3,10}                  end of \1 (NOTE: because you are using a
                           quantifier on this capture, only the LAST
                           repetition of the captured pattern will be
                           stored in \1)
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

This will satisfy your above-mentioned requirement.这将满足您的上述要求。 Hope it helps :)希望能帮助到你 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM