2013-03-10 28 views
0

我正在尋找一個正則表達式操作,以在Java中使用,它將提取第一個字,計算行上的數字數,然後將兩個數加在一起,用逗號分隔。用於提取第一個字和計數的java正則表達式操作

所以,例如:

"GAMESTATS 1(foul) 4(goals) 2(assists)" 

將被轉換成:

"GAMESTATS , 3" 

,因爲第一個字是 「GAMESTATS」,並且有三個數字( 「1」, 「4」和「2」)。

回答

1

像這樣的工作:

String s = "GAMESTATS 1(foul) 4(goals) 2(assists)"; 
String output = s.split(" ")[0] + "," + (s.split("\\d+").length - 1); 

,或者可能更有效:

String output = s.substring(0, s.indexOf(" ")) + "," + (s.split("\\d+").length - 1); 
+0

是的,這是我需要什麼eaxtly。謝謝 – user2152812 2013-03-10 04:38:52

0
String[] srt = line.split() 
StringBuffer sb = new StringBuffer(); 
sb.append(srt[0]); 
sb.append(","); 
int sum =0; 
for(int i=1;i<srt.length;i++){ 
    sum += // You will need to use a pattern like this [0-9]+ to extract the num 
} 
相關問題