繁体   English   中英

给定字符串想要将字符串的某些部分过滤到数组列表中

[英]Given string want to filter out certain part of string into an arraylist

我有字符串:

String s = #Jay125,150012 90,#Jay222,150043 00,  
  • 我想在 jay(125,222) 之后过滤掉值并将其添加到单独的ArrayList中。
  • 我想过滤掉 150012, 151243 一起添加到单独的ArrayList
  • 我想过滤掉 90,00 一起添加到单独的ArrayList

我尝试这样做,但它并没有完全达到我想要的效果

Pattern reg = Pattern.compile(",");
ArrayList<String> jay = reg.splitAsStream(s))    
                           .filter(role -> role.contains("Jay"))
                           .map(String::trim)
                           .collect(Collectors.toCollection(ArrayList::new));

如果我正确理解了您的情况,那么您将拥有一个String ,其模式为#Jay<Number>,<Number> <Number>形式,然后它会不断重复。 此外,您希望将此模式的每一位(jay 位、第一个数字位和第二个数字位)存储在三个单独的列表中。

正如评论中所建议的那样,您可以通过使用捕获组的正则表达式来识别这三个部分并在每次匹配时检索它们。

#(Jay\d+),(\d+) (\d+)

这是测试正则表达式的链接:

https://regex101.com/r/ULtDTu/1

这是一个带有实现的代码片段:

public class Main {
    public static void main(String[] args) {
        String s = "#Jay125,150012 90,#Jay222,150043 00,";
        Pattern pattern = Pattern.compile("#(Jay\\d+),(\\d+) (\\d+)");
        Matcher matcher = pattern.matcher(s);

        List<String> listJay = new ArrayList<>();
        List<String> listFirstSubNum = new ArrayList<>();
        List<String> listSecSubNum = new ArrayList<>();

        while (matcher.find()) {
            listJay.add(matcher.group(1));
            listFirstSubNum.add(matcher.group(2));
            listSecSubNum.add(matcher.group(3));
        }

        System.out.println(listJay);
        System.out.println(listFirstSubNum);
        System.out.println(listSecSubNum);
    }
}

你也可以在这里测试代码:

https://ideone.com/0hwpyl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM