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 ):
units = [
'tablespoon',
'teaspoon',
'cup',
'can',
'quart',
'gallon',
'pinch',
'pound',
'pint',
'fluid ounce',
'ounce'
]
joined_units = (units.collect{|u| u.pluralize} + units).join('|')
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}"