Multiply Integers Inside A String By An Individual

2019-08-31 08:01发布

问题:

I currently have the code below and it successfully returns all the numbers that are present in a string I have.

An example of the string would be say: 1 egg, 2 rashers of bacon, 3 potatoes.

    Pattern intsOnly = Pattern.compile("\\d+");
    Matcher matcher = intsOnly.matcher(o1.getIngredients());
    while (matcher.find()) {
        Toast.makeText(this, "" + matcher.group(), Toast.LENGTH_LONG).show();
    }

However, I would like to multiply these numbers by say four and then place them back in the original string. How can I achieve this?

Thanks in advance!

回答1:

I've never tried this, but I think appendReplacement should solve your problem



回答2:

Doing arithmetic is a little complicated while doing the find()

Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(test);
int start = 0;
int end = 0;
StringBuffer resultString = new StringBuffer();
while (matcher.find()) {
    start = matcher.start();
    // Copy the string from the previous end to the start of this match
    resultString.append(test.substring(end, start));
    // Append the desired new value
    resultString.append(4 * Integer.parseInt(matcher.group()));
    end = matcher.end();
}
// Copy the string from the last match to the end of the string
resultString.append(test.substring(end));

This StringBuffer will hold the result you are expecting.