Multiply Integers Inside A String By An Individual Value Using Regex

倾然丶 夕夏残阳落幕 提交于 2019-12-13 03:36:35

问题


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.



来源:https://stackoverflow.com/questions/18971006/multiply-integers-inside-a-string-by-an-individual-value-using-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!