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!

2
  • What does your string data look like and are you using Java platform? Commented Sep 22, 2013 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. Commented Sep 22, 2013 at 23:52

1 Answer 1

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());
}
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
Thought I'd post a new question so that you'd get the chance to earn more Reputation. Here's the link: stackoverflow.com/questions/18971006/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.