Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

ruby - Match a string against multiple patterns

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
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Regexp.union to combine them:

union(pats_ary) → new_regexp

Return a Regexp object that is the union of the given patterns, i.e., will match any of its parts.

So this will do:

re = Regexp.union(prefixes)

then you use re as your regex:

if name.match(re)
    #...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...