简体   繁体   English

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

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

I have string:我有字符串:

String s = #Jay125,150012 90,#Jay222,150043 00,  
  • I want to filter out value after jay(125,222) and add that to separate ArrayList .我想在 jay(125,222) 之后过滤掉值并将其添加到单独的ArrayList中。
  • I want to filter out 150012, 151243 together add that to separate ArrayList .我想过滤掉 150012, 151243 一起添加到单独的ArrayList
  • I want to filter out 90,00 together add that to separate ArrayList .我想过滤掉 90,00 一起添加到单独的ArrayList

I tried by doing this but it doesn't quite do what I want我尝试这样做,但它并没有完全达到我想要的效果

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

If I have understood correctly your case, you're having a String whose pattern is in the form #Jay<Number>,<Number> <Number> and then it keeps repeating itself.如果我正确理解了您的情况,那么您将拥有一个String ,其模式为#Jay<Number>,<Number> <Number>形式,然后它会不断重复。 Also, you would like to have every bit of this pattern (jay bit, first number bit and second number bit) stored in three separate lists.此外,您希望将此模式的每一位(jay 位、第一个数字位和第二个数字位)存储在三个单独的列表中。

As suggested in the comments, you could achieve this with a regex using capturing groups to identify the three portions and retrieve them at every match.正如评论中所建议的那样,您可以通过使用捕获组的正则表达式来识别这三个部分并在每次匹配时检索它们。

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

Here is a link to test the regex:这是测试正则表达式的链接:

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

Here is a code snippet with the implementation:这是一个带有实现的代码片段:

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

You can also test the code here:你也可以在这里测试代码:

https://ideone.com/0hwpyl https://ideone.com/0hwpyl

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

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