问题
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