簡體   English   中英

Java中用戶名的正則表達式(RegEx)

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

如何在Java中形成用戶名字符串的RegEx?

練習規則:

  1. 只有 3 - 10 個字符。
  2. 只有'a'-'z'、'A'-'Z'、'1'-'9'、'_'和'.' 被允許。
  3. '_' 和 '。' 只能出現0到2次。
  • "abc_._" =假
  • "abc..." = 假
  • "abc__" = 真
  • "abc.." = 真
  • "abc_." = 真

如果我不使用正則表達式,它會更容易。


在不考慮“1”-“9”的情況下,我嘗試了以下正則表達式,但它們不起作用。

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

我的功能:

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;
}

我應該使用什么正則表達式?

如果我從CS類記得很清楚,這是不可能創建一個單一的正則表達式來滿足所有這些要求。 因此,我會對每個條件進行單獨檢查。 例如,此正則表達式檢查條件 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;
}

順便說一句,請注意允許您在 Java 中重用正則表達式的模式(性能增益,因為編譯正則表達式的成本很高)。

正則表達式不能做你想做的事情的原因(如果我沒記錯的話)是這個問題需要上下文無關語法,而正則表達式是常規語法。 鉸更多

首先, || 不是這個問題所必需的,實際上並沒有做你認為的那樣。 我只見過它成組用於正則表達式(比如如果你想匹配HelloWorld ,你會匹配(Hello|World)(?:Hello|World) ,在這些情況下你只使用一個|


接下來,讓我解釋為什么您嘗試過的每個正則表達式都不起作用。

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

字符類中的范圍運算符不會被解釋為范圍運算符,而只會表示構成范圍運算符的文字。 此外,嵌套的字符類只是簡單地組合在一起。 所以這實際上等於:

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

所以它將匹配以下 3-10 個的組合: a - z , A - Z , 0 , 2 , { , } , . , | , 和_

這不是你想要的。


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

這將匹配 3 到 10 個a - zA - Z ,然后是兩個管道,然后是_| ,或. 0~2次。 也不是你想要的。


做到這一點的簡單方法是將需求分成兩部分並基於這些創建兩個正則表達式字符串:

  1. 只有 3 - 10 個字符,其中只有 'a'-'z'、'A'-'Z'、'1'-'9'、'_' 和 '.' 被允許。
  2. '_' 和 '。' 只能出現0到2次。

第一個要求非常簡單:我們只需要創建一個包含所有有效字符的字符類,並對可以出現的字符數進行限制:

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

然后我會驗證 '_' 和 '.' 出現0到2次:

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

或者

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

不幸的是,我沒有足夠的經驗來弄清楚單個正則表達式的樣子......但這些至少是相當可讀的。

請試試這個:[[aZ][0-9] [._]?[[aZ][0-9] [._]?[[aZ][0-9]*

尼可

編輯:你是對的。 然后幾個正則表達式: Regex1: ^[\\w.]{3-10}$ Regex2: ^[[aZ][0-9]] [_.]?[[aZ][0-9]] [_.] ?[[aZ][0-9]]*$

我希望我什么都沒忘記!

可能不優雅,但你可以試試這個:

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

這是解釋:

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

這將滿足您的上述要求。 希望能幫助到你 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM