匹配多个模式的string
如何在Ruby中使用正则expression式匹配多个模式的string。
我想看看一个string是否包含在前缀数组中,这是行不通的,但我认为它至less展示了我正在尝试做什么。
# example: # prefixes.include?("Mrs. Kirsten Hess") prefixes.include?(name) # should return true / false prefixes = [ /Ms\.?/i, /Miss/i, /Mrs\.?/i, /Mr\.?/i, /Master/i, /Rev\.?/i, /Reverend/i, /Fr\.?/i, /Father/i, /Dr\.?/i, /Doctor/i, /Atty\.?/i, /Attorney/i, /Prof\.?/i, /Professor/i, /Hon\.?/i, /Honorable/i, /Pres\.?/i, /President/i, /Gov\.?/i, /Governor/i, /Coach/i, /Ofc\.?/i, /Officer/i, /Msgr\.?/i, /Monsignor/i, /Sr\.?/i, /Sister\.?/i, /Br\.?/i, /Brother/i, /Supt\.?/i, /Superintendent/i, /Rep\.?/i, /Representative/i, /Sen\.?/i, /Senator/i, /Amb\.?/i, /Ambassador/i, /Treas\.?/i, /Treasurer/i, /Sec\.?/i, /Secretary/i, /Pvt\.?/i, /Private/i, /Cpl\.?/i, /Corporal/i, /Sgt\.?/i, /Sargent/i, /Adm\.?/i, /Administrative/i, /Maj\.?/i, /Major/i, /Capt\.?/i, /Captain/i, /Cmdr\.?/i, /Commander/i, /Lt\.?/i, /Lieutenant/i, /^Lt Col\.?$/i, /^Lieutenant Col$/i, /Col\.?/i, /Colonel/i, /Gen\.?/i, /General/i ]
使用Regexp.union
来结合它们:
union(pats_ary)→new_regexp
返回一个
Regexp
对象,该对象是给定模式的联合,也就是说,将匹配其任何部分。
所以这将做到:
re = Regexp.union(prefixes)
那么你使用re
作为你的正则expression式:
if name.match(re) #...
如果可以使用单个string,那么编写包含可能值的正则expression式可能会更快。
例如
/(Mr \。| Mrs \。| ...)/。match(name)