简体   繁体   中英

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 .
  • I want to filter out 150012, 151243 together add that to separate ArrayList .
  • I want to filter out 90,00 together add that to separate 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. 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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