2011-10-02 140 views
0

我需要使用正則表達式驗證字符串,字符串必須像「createRobot(x,y)」,其中x和y是數字。使用Java驗證正則表達式

我有類似

String ins; 

    Pattern ptncreate= Pattern.compile("^createRobot(+\\d,\\d)"); 
    Matcher m = ptncreate.matcher(ins); 
    System.out.println(m.find()); 

但不工作

你能幫助我嗎?

謝謝。

+3

如果它應該是createRobot,你爲什麼在表達中只有「創造」? – stivlo

+0

我忘了發佈它,但在代碼中我有「createRobot」,對不起 – JuanS

回答

4

您忘記了您的模式中的單詞Robot。此外,括號在正則表達式特殊字符,應該+後不(放在\d後:

Pattern.compile("^createRobot\\(\\d+,\\d+\\)$") 

請注意,如果您想驗證輸入應該只包括本"createRobot" -string,你心如做:

boolean success = s.matches("createRobot\\(\\d+,\\d+\\)"); 

其中s是要驗證String。但是,如果你想獲取相匹配的數字,你需要使用模式/匹配器:

Pattern p = Pattern.compile("createRobot\\((\\d+),(\\d+)\\)"); 
Matcher m = p.matcher("createRobot(12,345)"); 
if(m.matches()) { 
    System.out.printf("x=%s, y=%s", m.group(1), m.group(2)); 
} 

正如你所看到的,調用Matcher.matches()(或Matcher.find())後,就可以檢索ñ th match-group through group(n)

+0

非常感謝,真的有用,有什麼方法可以獲得數字「x」和「y」? – JuanS

+0

@JuanS,我在我的回答中加入了這個。別客氣。 –

+0

這就是我正在尋找的,謝謝!最後一個問題,你可以給我一個網頁或其他資源,我可以瞭解更多關於正則表達式? – JuanS

0

必須(前添加\因爲(在正則表達式是特殊的羣體性格

的正則表達式pattren是: ^創建(\ d + \ d +)