2013-05-13 43 views
0

我想實現其實很簡單解析兩個數字正則表達式從行

V123,V20 
10,9999 
100,V220 

等等

基本上多雙帶有前導字母/零的數字。 我希望能夠使用正則表達式來解析它們,我已經在Java中迄今發現的是:

Pattern p = Pattern.compile(".*([1-9](?:\\d{0,2})).*",Pattern.MULTILINE); 
Matcher m = p.matcher("V999,V50"); 
System.out.println(m.matches()); - return true 
System.out.println(m.groupCount()); --> this one returns 0 

任何幫助將不勝感激,謝謝 。

+1

是不是(i)拆分和(ii)刪除非數字字符更簡單? – assylias 2013-05-13 18:58:31

+0

你想做什麼?你所說的只是你想「_parse them_」。這可能意味着什麼。 – jahroy 2013-05-13 19:00:54

+0

您的預期輸出來自以上輸入? – anubhava 2013-05-13 21:10:40

回答

1
public static void main(String[] args) throws IOException { 
    String[] a = new String[] {"V123,V20", "10,9999", "100,V220"}; 

    for (String s: a) { 
     Pattern p = Pattern.compile("[\\D0]*(\\d*)[\\D0]*(\\d*)",Pattern.MULTILINE); 
     Matcher m = p.matcher(s); 
     System.out.println(m.matches()); 
     System.out.println(m.group(1) + ", " + m.group(2)); 
    } 
} 

希望它有幫助!

編輯

PS:如果你有尾隨字母,您可以添加\\ d到底:

"[\\D0]*(\\d*)[\\D0]*(\\d*)[\\D]* 
+0

謝謝,這是一個很大的幫助! – 2013-05-14 20:02:30

0

我會做這樣

Matcher m = Pattern.compile("\\d+").matcher(str); 
    while(m.find()) { 
     int i = Integer.parseInt(m.group()); 
    }