2010-09-09 47 views
1

獲取數字我有一個字符串,看起來像這樣從分隔列表

String read = "1130:5813|1293:5803|1300:5755|1187:5731|" 

正如你可以看到有4對整數值。

我想有值添加到列表中像這樣

a = 1130 
b = 5813 

groupIt pair = new groupIt(a,b); 
List<groupIt> group = new ArrayList<groupIt>(); 
group.add(pair); 

我如何能做到這一點的4對字符串。

可以使用Pattern.compile()這個嗎?

回答

3

你爲什麼不使用

String[] tokens = read.split("\\|"); 
for (String token : tokens) { 
    String[] params = token.split(":"); 
    Integer a = Integer.parseInt(params[0]); 
    Integer b = Integer.parseInt(params[1]); 

    // ... 

} 
+1

PARAMS應該是一個字符串[]。你可能不得不跳過|,因爲split接受一個正則表達式。 – gpeche 2010-09-09 10:44:40

+0

@gpeche你是對的。我剛剛修改了我的回覆。 – mgamer 2010-09-09 10:50:26

+0

是的,我也可以這樣做。感謝您的幫助..它的作品。事實上,我試圖與模式..但是這個工程。 – jimmy 2010-09-09 10:56:18

0

只是良好的措施,這裏是你的正則表達式:

public class RegexClass { 
    private static final Pattern PATTERN = Pattern.compile("(\\d{4}):(\\d{4})\\|"); 

    public void parse() { 
     String text = "1130:5813|1293:5803|1300:5755|1187:5731|"; 
     Matcher matcher = PATTERN.matcher(text); 
     int one = 0; 
     int two = 0; 
     while(matcher.find()) { 
      one = Integer.parseInt(matcher.group(1)); 
      two = Integer.parseInt(matcher.group(2)); 

      // Do something with them here 
     } 
    } 
} 

不過,我認爲邁克爾是正確的:他的解決方案是更好!

祝你好運...