2010-09-09 92 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 
     } 
    } 
} 

不过,我认为迈克尔是正确的:他的解决方案是更好!

祝你好运...