使用正则表达式在字符串中查找多个整数

时间:2013-09-22 23:46:02

标签: android regex string int matcher

我目前有以下代码:

    Pattern intsOnly = Pattern.compile("\\d+");
    Matcher matcher = intsOnly.matcher(o1.getIngredients());
    matcher.find();
    String inputInt = matcher.group();

目前发生的是使用正则表达式,它找到字符串中的第一个整数并将其分开,以便我可以对其执行操作。我用来查找内部整数的字符串有很多整数,我希望它们都是分开的。我如何调整此代码,以便它还记录字符串中的其他整数,而不仅仅是第一个。

提前致谢!

1 个答案:

答案 0 :(得分:2)

在您发布的代码中:

matcher.find();
String inputInt = matcher.group();

您将整个字符串与一次调用相匹配。然后将第一个数字匹配分配给字符串inputInt。例如,如果您有以下字符串数据,则返回的内容仅为1

1 egg, 2 bacon rashers, 3 potatoes

您应该使用while循环来循环匹配。

Pattern intsOnly = Pattern.compile("\\d+");
Matcher matcher = intsOnly.matcher(o1.getIngredients());
while (matcher.find()) {
  System.out.println(matcher.group());
}