2017-03-15 87 views
-1

我該如何去檢查一個字符串以確保第一個字符是字母,其餘的都是數字?格式檢查字符串是否與特定格式匹配

例子中,我檢查

ZA825 
FD8821 
TT42212333 

它不只要第2是字母,其餘是數字關係的長度。

+5

開始學習[正則表達式](https://docs.oracle.com/javase/tutorial/essential/regex/)。 –

+0

'str.matches(「[A-Z] {2} \\ d *」)' – 4castle

回答

0

最簡單的實現方法是通過正則表達式。 Java通過類Pattern,發現hereMatcher,發現here來做到這一點。

public bool matches(String s) { 
    Pattern p = Pattern.compile("([A-Z]{2}\\d+)"); 
    Matcher m = p.matcher(s); 

    return m.matches(); 
} 
0

使用regular expressions

要簡單地驗證字符串中的模式匹配等中記載的一個:

//        two letters 
//       / \ 
boolean valid = string.matches("[A-Z]{2}\\d+"); 
//          \/
//        one or more digits 

如果你必須這樣做檢查多次或有進一步的需求(例如提取子),使用Pattern類。

相關問題