Can I ignore rest of the list when the pattern occurs java?

This is the Code:

private List listaPunktowInt(List lista) {
    
    String liniaString="";
    List<Integer> list=new ArrayList();
    Iterator<String> it=lista.iterator();
    while(it.hasNext()) {
        liniaString=it.next();
        
        if(Pattern.matches("\\d*",liniaString)) {
            list.add(Integer.parseInt(liniaString));
        }
    }
    
    //Collections.sort(list);
    //Collections.reverse(list);
    System.out.println(list);
    return list;
}

Input:[56, 4, 2 2022 04 06, 1, 1, 1]

Output:[56, 4, 1, 1, 1]

I want "2" to be included as well but the rest ("2022 04 06") to be ignored, is it possible?

>Solution :

Right now Pattern.matches checks if the whole string matches \d* (i.e. only contains digits). That’s very easy with the static Pattern.matches method.

To do anything more involved with regex, you should use a Matcher (which is the thing that is about a single use of a regex, i.e. it’s the combination of a pattern like \d* and some input string like liniaString). It’ still used under the hood, but Pattern.matches hides that fact from you.

So your code could look like this (I also fixed the types and added static since the method doesn’t depend on any state of the object):

private static List<Integer> listaPunktowInt(List<String> lista) {
    Pattern pattern = Pattern.compile("^\d+");
    List<Integer> list=new ArrayList<>();
    for (String liniaString : lista) {
        Matcher matcher = pattern.matcher(liniaString);
        if(matcher.find()) {
            list.add(Integer.parseInt(matcher.group()));
        }
    }
    return list;
}

Right now this simply takes as many digits from the beginning as possible and ignores whatever comes after them (characters, space, end of string, …). If you want something other than that, you can adapt the pattern used.

Leave a Reply