Finding Multiple Integers Inside A String Using Regex

巧了我就是萌 提交于 2019-12-13 04:45:19

问题


I currently have this code below:

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

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.

Thanks in advance!


回答1:


In your posted code:

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

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());
}


来源:https://stackoverflow.com/questions/18949914/finding-multiple-integers-inside-a-string-using-regex

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