androidserver-response

Clip all the data except a certain data from server response to use in app


I am getting a response from the server as below,

<p style="font-family:Arial, Helvetica, sans-serif; font-size:18px;"> <strong>XXX Pvt Ltd. has been used 3 times.The contact information for XXX can only be viewed -4 more times on App until it expires. Please urgently verify the information.</strong></p>

Here I would need the integer value -4 if it is negative or 4 if it is positive. In case it is negative I would like to get it with the negative sign.

Is there any way to clip all the text values and just get a part of the response from the server in android?

I actually need the count of times we can see the info above in my app.

I tried researching and gone through some links as,

Remove all occurrences of \ from string

How to replace the characher `\n` as a new line in android

How to strip or escape html tags in Android

However, none of this could actually help me in achieving what I want.

Please, can anyone help?


Solution

  • You can get the last digit from a String using this:

    String s = "";
    String str = "<p style=\\\"font-family:Arial, Helvetica, sans-serif; font-size:18px;\\\"> <strong> This is the information you need 5 times you can see.</strong></p>";
    Pattern p = Pattern.compile("(\\d+)(?!.*\\d)");
    Matcher m = p.matcher(str);
    if (m.find()) {
        s = m.group();
    }
    int number = Integer.parseInt(s);
    

    number is the number from your html string.

    See: https://regex101.com/r/jAFJiL/1

    Edit, multiple numbers:

    Here is a small ugly piece of code I wrote for you. This gets all numbers from a String and removes the first one. (The 18px from your input):

    String str = "<p style=\"font-family:Arial, Helvetica, sans-serif; font-size:18px;\"> <strong>XXX Pvt Ltd. has been used 3 times.The contact information for XXX can only be viewed 4 more times on App until it expires. Please urgently verify the information.</strong></p>";
    boolean previousWasDigit = false;
    
    ArrayList<Integer> numbers = new ArrayList<>();
    String number = "";
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (Character.isDigit(c)) {
            if (previousWasDigit) {
                number += c;
            } else {
                number = Character.toString(c);
            }
            previousWasDigit = true;
        } else {
           if (previousWasDigit) {
               numbers.add(Integer.parseInt(number));
           }
           previousWasDigit = false;
        }
    }
    numbers.remove(0); // we remove the first digit (18) here
    // numbers contains the digits of your string