tags:

views:

58

answers:

1

I need a regular expression that, given an ingredient line, will tell me the quantity of that ingredient. Here are some sample values:

  • 8 ounces semisweet chocolate
  • 6 eggs
  • 3/4 cup sugar
  • 1-tablespoon espresso powder
  • 1/2 cup Dutch processed baking cocoa
  • 1/4 cup unsweetened cocoa
  • 1/2 cup confectioners' sugar
  • 2 cups heavy cream
  • 2 to 4 dried scallops (optional)
  • 1 1/2 cups carrots
  • Raspberry and apricot preserves

Whenever a quantity exists (all the examples except for the last) it needs to get the quantity. So, for the first example "8 ounces of semisweet chocolate" it needs to return "8 ounces".

How do I do this using PHP regex?

+1  A: 

For your examples (and a few others I can think of),

^[ \d/.-]*(?:to\s+[ \d/.-]*)?(?:ounces?|cups?|(?:table|tea)spoons?)?

would work.

If you want to avoid to capture a trailing space (as this regex would do after a number not followed by a unit), add (?=\s) to the end of the regex.

Tim Pietzcker
would this miss the 6 on eggs though?
polyhedron
@polyhedron: No, why should it? The units are optional.
Tim Pietzcker