0

我目前有下面的代码,它成功地返回了我拥有的字符串中存在的所有数字。

字符串的一个例子是:1 个鸡蛋,2 个培根,3 个土豆。

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

但是,我想将这些数字乘以四,然后将它们放回原始字符串中。我怎样才能做到这一点?

提前致谢!

4

2 回答 2

0

我从未尝试过,但我认为appendReplacement应该可以解决您的问题

于 2013-09-24T00:59:31.503 回答
0

做 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));

此 StringBuffer 将保存您期望的结果。

于 2013-09-24T01:08:47.017 回答