對於使用Ruby的正則表達式,我有點新奇(或者我認爲一般情況下是正則表達式),但我想知道是否有一種實用的方法來匹配使用數組的字符串?Ruby正則表達式匹配數組中的字符串?
讓我解釋,說我在這種情況下配料表:
1 1/3 cups all-purpose flour
2 teaspoons ground cinnamon
8 ounces shredded mozzarella cheese
最終,我需要將原料分成各自的「量測量」和「成分名」,所以喜歡在的2 teaspoons ground cinnamon
的情況下,將因此而不必像一個巨大的長正則表達式拆分爲「8 ounces
,並且shredded mozzarella cheese
:(cup\w*|teaspoon\w*ounce\w* .......)
,我該如何使用一個數組來保存正則表達式之外的值
更新
我這樣做(感謝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}"
我也使用這種方法,做了一些調整: Regexp.union(測量)代替Regexp.new(measurements.join(「|」)),結果相同,非常乾淨 – Coelhone 2013-02-20 14:39:28