有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从单独的列表中获取数字

我有一根像这样的线

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()进行此操作吗


共 (2) 个答案

  1. # 1 楼答案

    这是您的正则表达式,仅供参考:

    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
            }
        }
    }
    

    然而,我确实认为Michael是正确的:他的解决方案更好

    祝你好运

  2. # 2 楼答案

    你为什么不使用

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