我对Ruby的正则表达式有点陌生(或者我一般认为正则表达式),但是我想知道是否存在一种实用的方法来使用数组匹配字符串?

让我解释一下,说在这种情况下,我有一个配料表:

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

最终,我需要将成分拆分为各自的“数量和度量”和“成分名称”,因此像2 teaspoons ground cinnamon一样,将被拆分为“8 ouncesshredded 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}"

最佳答案

就我个人而言,我只是以编程方式构建正则表达式,您可以执行以下操作:

ingredients = [...]
recipe = Regexp(ingredients.join("|"), true) # Case-insensitive

或使用union方法:
recipe = Regexp.union(ingredients)
recipe = /#{regex}/i

…然后使用recipe正则表达式。

只要您保存它并且不重新创建它,它就应该相当有效。

10-05 20:22
查看更多