【问题标题】:Multiply Integers Inside A String By An Individual Value Using Regex使用正则表达式将字符串中的整数乘以单个值
【发布时间】:2013-09-29 01:02:18
【问题描述】:

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

字符串的一个例子是: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();
    }

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

提前致谢!

【问题讨论】:

    标签: android regex string int multiplication


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      做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 将保存您期望的结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-25
        相关资源
        最近更新 更多