Matching Ruby regex strings from an array?

I'm kind of new to regular expressions with Ruby (or, I suppose, regex in general), but I was wondering if there is a pragmatic way to match strings using an array?

Let me explain, say, I have a list of ingredients in this case:

1 1/3 cups all-purpose flour
2 teaspoons ground cinnamon
8 ounces shredded mozzarella cheese

Ultimately, I need to divide the ingredients into the corresponding โ€œquantity and dimension" and "ingredient name", as in the case it 2 teaspoons ground cinnamonwill be divided into " 8 ouncesand shredded mozzarella cheese.

So, instead of having a very long regex: (cup\w*|teaspoon\w*ounce\w* ....... )how can I use an array to store these values โ€‹โ€‹outside the regex?


Update

I did this (thanks cwninja ):

  # I think the all units should be just singular, then 
  # use ruby function to pluralize them.

units = [
  'tablespoon',
  'teaspoon',
  'cup',
  'can',
  'quart',
  'gallon',
  'pinch',
  'pound',
  'pint',
  'fluid ounce',
  'ounce'
  # ... shortened for brevity
]

joined_units = (units.collect{|u| u.pluralize} + units).join('|')

# There are actually many ingredients, so this is actually an iterator
# but for example sake we are going to just show one.
ingredient = "1 (10 ounce) can diced tomatoes and green chilies, undrained"

ingredient.split(/([\d\/\.\s]+(\([^)]+\))?)\s(#{joined_units})?\s?(.*)/i)

, , , , .

puts "measurement: #{arr[1]}"
puts "unit: #{arr[-2] if arr.size > 3}"
puts "title: #{arr[-1].strip}"
+5
2

, :

= [...] MEASUREMENTS_RE = Regexp.new(measurement.join( "|" ))

... regexp.

, .

+22

a :

a.each do |line|
    parts = /^([\d\s\.\/]+)\s+(\w+)\s+(.*)$/.match(line)
    # Do something with parts[1 .. 3]
end

:

a = [
    '1 1/3 cups all-purpose flour',
    '2 teaspoons ground cinnamon',
    '8 ounces shredded mozzarella cheese',
    '1.5 liters brandy',
]
puts "amount\tunits\tingredient"
a.each do |line|
    parts = /^([\d\s\.\/]+)\s+(\w+)\s+(.*)$/.match(line)
    puts parts[1 .. 3].join("\t")
end
+3

All Articles