1

I have list with combination of letters, digits and special characters. I need to extract the digits from string and store them in the same list.

I tried with below code

       List<String> list = new LinkedList<String>();
       list.add("132144, Test");
       list.add("76876295, Test2");
       //tried with replaceAll();
       list.replaceAll(x->x.replace("[^0-9]",""));
       //tried collection
       Collections.replaceAll(list, "\\W+", "");
       System.out.println(list);

Getting the output as [132144, Test,76876295, Test2], need output as [132144,76876295]

1
  • Do you want to include the 2 of the text Test2 into the result? Commented Dec 6, 2019 at 7:24

4 Answers 4

3

Stream the list, map each entry using a regular expression (\\D matches non-digits) to replace all non-digits with nothing. Collect that back into your original list (assuming you need to keep the new values only). Like,

list = list.stream().map(s -> s.replaceAll("\\D+", ""))
        .collect(Collectors.toList());
System.out.println(list);

Outputs (as requested)

[132144, 768762952]

Your current input doesn't have such a case, but you might also filter out any empty String(s) after applying the regex.

list = list.stream().map(s -> s.replaceAll("\\D+", ""))
        .filter(s -> !s.isEmpty()).collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

0

You can do like this:

    String line = "This order was32354 placed OK?8377jj";
    String regex = "[^\\d]+";

    String[] str = line.split(regex);

    for(int i=0;i<str.length; i++) {
        System.out.println(str[i]);
    }

Output:

32354
8377

Hope this helps.

Comments

0

public static void main(String[] args) {

    List<String> list = new LinkedList<String>();
    List<String> list1 = new LinkedList<String>();
    list.add("132144, Test");
    list.add("76876295, Test2");
    for(String s:list)
        list1.add(retriveDigits(s));
    System.out.println(list1);
}

private static String retriveDigits(String str) {
    return str.replaceAll("[^0-9]*", "");

}

}

Please find above class, I think that will help you.

Comments

0

you can use NumberUtils.isNumber() in stream like this:

list = list.stream()
           .filter(NumberUtils::isNumber)
           .collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.