将一个字符串与多个模式匹配 [英] Match a string against multiple patterns
本文介绍了将一个字符串与多个模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 ruby 中的正则表达式将字符串与多个模式匹配.
How can I match a string against multiple patterns using regular expression in ruby.
我正在尝试查看一个字符串是否包含在前缀数组中,这不起作用,但我认为它至少展示了我正在尝试做的事情.
I am trying to see if a string is included in an array of prefixes, This is not working but I think it demonstrates at least what I am trying to do.
# 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
将它们组合起来:
Use Regexp.union
to combine them:
union(pats_ary) → new_regexp
返回一个 Regexp
对象,它是给定 patterns 的并集,即,将匹配其任何部分.
Return a Regexp
object that is the union of the given patterns, i.e., will match any of its parts.
这样就可以了:
re = Regexp.union(prefixes)
然后你使用 re
作为你的正则表达式:
then you use re
as your regex:
if name.match(re)
#...
这篇关于将一个字符串与多个模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文