简体   繁体   English

将字符串与多个模式匹配

[英]Match a string against multiple patterns

How can I match a string against multiple patterns using regular expression in ruby. 如何在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
]

Use Regexp.union to combine them: 使用Regexp.union将它们组合在一起:

union(pats_ary) → new_regexp union(pats_ary)→new_regexp

Return a Regexp object that is the union of the given patterns , ie, will match any of its parts. 返回一个Regexp对象,它是给定模式的并集 ,即匹配任何部分。

So this will do: 所以这将做:

re = Regexp.union(prefixes)

then you use re as your regex: 然后你用re作为你的正则表达式:

if name.match(re)
    #...

If you can use a single string, it might be faster to write a regex containing the possible values. 如果可以使用单个字符串,则编写包含可能值的正则表达式可能会更快。

eg 例如

/(Mr\.|Mrs\.| ... )/.match(name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM