Replace Arraylist with everything except for numbers in Java

77 views Asked by At

I have a Arraylist, like this:

ArrayList<String> moisturizersPrices = [Price: Rs. 365, Price: Rs. 299, Price: Rs. 12, Price: 220, Price: 95, Price: 216]

for that I am using following logic:

moisturizersPrices.replaceAll("[^0-9.]", "")

and it is returning me something like this:

[.365, .299, .12, 220, 95, 216] 

Now I want to remove all characters from there, except for numeric, such as it should be giving me results like this:

[365, 299, 12, 220, 95, 216] 

I need to know, where I am making mistake.

2

There are 2 answers

0
Islam Elbanna On BEST ANSWER

You could try a Pattern match like

List<String> moisturizersPrices = List.of(
    "Price: Rs. 365",
    "Price: Rs. 299", 
    "Price: Rs. 12", 
    "Price: 220", 
    "Price: 95", 
    "Price: 216"
);
Pattern p = Pattern.compile("[0-9]+$");
List<Integer> numbers = moisturizersPrices.stream()
    .map(p::matcher)
    .filter(Matcher::find)
    .map(m -> Integer.parseInt(m.group()))
    .collect(Collectors.toList());
[365, 299, 12, 220, 95, 216]
0
WJS On

You can do it very simply like this. Just replace every non-Digit (\\D) with an empty string.

 List<String> moisturizers = new ArrayList<>(
         List.of("Price: Rs. 365", "Price: Rs. 299", "Price: Rs. 12",
                 "Price: 220", "Price: 95", "Price: 216"));

 moisturizers.replaceAll(str->str.replaceAll("\\D",""));
 System.out.println(moisturizers);

prints

[365, 299, 12, 220, 95, 216]

If you want to convert them to a List<Integer>, do it like this.

List<Integer> results = moisturizers.stream()
        .map(str -> Integer.parseInt(str.replaceAll("\\D", "")))
        .toList();
System.out.println(results);

prints the same as above

If you have other digits elsewhere, then use the following regex. It will replace all characters up to the digits at the end of the string with those captured in the parentheses. The $1 is a back reference to those digits.

str.replaceAll(".*?(\\d+)$", "$1")