查找多个整数内的字符串使用正则表达式 [英] Finding Multiple Integers Inside A String Using Regex

查看:153
本文介绍了查找多个整数内的字符串使用正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有低于这个code:

I currently have this code below:

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

目前是什么情况是使用正则表达式,它发现一个字符串中的第一个整数,它分开,这样我可以开展它的行动。我使用发现里面整数字符串有很多的整数,我想他们都分开。我该如何调整这个code,这样它也从字符串记录等整数,不只是第一个。

What currently happens is that using Regex, it finds the first integer inside a string and separates it so that I can carry out actions on it. The string that I am using to find integers inside of has many integers and I want them all separate. How can I tweak this code so that it also records the other integers from the string, not just the first one.

在此先感谢!

推荐答案

在您的贴code:

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

您是匹配整个字符串用一个电话找到。然后分配位数的第一个匹配你的字符串 inputInt 。因此,举例来说,如果你有以下字符串数据,你的回报将只有 1

You are matching the whole string with a single call to find. And then assigning the first match of digits to your String inputInt. So for example, if you have the below string data, your return will only be 1.

1 egg, 2 bacon rashers, 3 potatoes

您应该使用,而循环来在你的比赛。

You should use a while loop to loop over your matches.

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

这篇关于查找多个整数内的字符串使用正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆