2016-01-22 160 views
-2

如何驗證Java中的此字符串輸入?驗證字符串輸入

兩個字母后跟三個數字和一個字母。最後一封信只能是B的商業帳戶或N的非商業帳戶

一個例子是'JB213B'或'JB231N'。

編輯:對,我現在使用正則表達式,謝謝。

雖然現在我提出如何實際進行驗證,這裏是我迄今爲止

  System.out.println("Enter your reference"); 
      String reference = keyboard.next(); 
      String regex = "[A-Z]{2}[0-9]{3}[B|N]"; 
      boolean match = reference.matches(regex); 
      while (!match) 
      { 
       System.out.println("That isn't a valid reference"); 
       reference = keyboard.next(); 
       match = reference.matches(regex); 
      } 
+0

遍歷字符串的每個字符,並確保它是它應該是什麼?或者,也許正則表達式會起作用。 –

+0

我希望能有一種不太重要的方式,而不是迭代每個角色,但是謝謝。 –

+0

使用正則表達式無法正常工作的原因是什麼? –

回答

2

你可以做到這一點使用正則表達式。

在這種情況下的表達。將^[A-Z]{2}[0-9]{3}[B|N]$

ThisString類的.matches()方法的參考。

同樣,您也可以使用Pattern類來查找匹配項。 This是一個參考。

用法:

String strToTest = "AB123B"; 
    String pattern = "^[A-Z]{2}[0-9]{3}[B|N]$"; 
    Pattern p = Pattern.compile(patern); 
    Matcher m = p.matcher(strToTest); 
    boolean b = m.matches(); 

性能比較:

哪個是更好的 「使用正則表達式」 或 「使用字符串比較」?

這個問題總是有爭議的。但是我發現,瞭解需求的複雜性在任何情況下都是無用的。

如果有很多需要使用正則表達式可以跳過的字符串比較,那麼我會用正則表達式去。

但是還應該考慮使用多個和/或複雜的正則表達式會影響性能,因爲正則表達式的評估對編譯器來說也是一個單調乏味且複雜的過程(與字符串操作相比)。

另一方面,使用字符串比較也容易出錯,因爲我們直接處理索引並剝離不必要的部分。

2

使用如下的正則表達式。

String st = "JB213B"; 
String regex= "[A-Z]{2}\\d{3}[BN]"; 

boolean match = st.matches(regex); 
+0

那麼,這是否會驗證輸入? 'System.out.println(「Enter your reference」); String reference = keyboard.next(); String regex =「[A-Z] {2} [0-9] {3} [B | N]」; boolean match = reference.matches(regex); while(match = false) System.out.println(「This is not a valid reference」); reference = keyboard.next(); match = reference.matches(regex); }' –

+0

是的,看起來是正確的,除了(match == false),not(match = false),更好的是,編寫_(!match)_而不是。我剛剛編輯你的文章來改變它。 – Berger

+0

謝謝你的回答,現在我可以停止把我的頭髮扯到這樣愚蠢的東西上:') –

3

只是可以肯定有人打架非正則表達式的可能性:

public boolean isValid(String s) { 
    return s.length() == 6 && 
     s.charAt(0) >= 'A' && s.charAt(0) <= 'Z' && 
     s.charAt(1) >= 'A' && s.charAt(1) <= 'Z' && 
     s.charAt(2) >= '0' && s.charAt(2) <= '9' && 
     s.charAt(3) >= '0' && s.charAt(3) <= '9' && 
     s.charAt(4) >= '0' && s.charAt(4) <= '9' && 
     (s.charAt(5) == 'B' || s.charAt(5) == 'N'); 
} 
3

您可以將字符串比較使用匹配()方法的正則表達式。

// Match A-Z twice, 0-9 three times, and B or N once 
String myString = "JB213B"; 
String myPattern = "[A-Z]{2}[0-9]{3}[BN]{1}"; 
if(myString.matches(myPattern){ 
    // Do continuing logic 
} else { 
    // Do error logic 
}