moteutsch
moteutsch

Reputation: 3831

Get numeric expression with unit of measure from strings describing recipe ingredients

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

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?

Upvotes: 3

Views: 222

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336108

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.

Upvotes: 2

Related Questions