0

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!

VLAZ
  • 26,331
  • 9
  • 49
  • 67
edwoollard
  • 12,245
  • 6
  • 43
  • 74
  • What does your string data look like and are you using Java platform? – hwnd Sep 22 '13 at 23:51
  • It's a set of ingredients. An example would be like this: 1 egg, 2 bacon rashers, 3 potatoes. I need to find all three of those numbers, in that example. Currently I'm only pulling back the first. – edwoollard Sep 22 '13 at 23:52

1 Answers1

2

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());
}
hwnd
  • 69,796
  • 4
  • 95
  • 132
  • Thanks very much man. It works perfectly and reads out all the relevant numbers. I'm new to Regex and wasn't really thinking straight. I appreciate your help. – edwoollard Sep 23 '13 at 08:47
  • Now that I've found the integers, I want to multiply them by a value and then place them back in the original string with the new multiplied number. Can you help me to achieve this? How should I tackle that? – edwoollard Sep 24 '13 at 00:12
  • Thought I'd post a new question so that you'd get the chance to earn more Reputation. Here's the link: http://stackoverflow.com/questions/18971006/multiply-integers-inside-a-string-by-an-individual-value-using-regex – edwoollard Sep 24 '13 at 00:21