38
如何在Ruby中使用正則表達式匹配多個模式的字符串。匹配多個模式的字符串
我想看看一個字符串是否包含在一個前綴數組中,這是行不通的,但我認爲它至少演示了我正在嘗試做什麼。
# 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
]
+1尼斯之一。我會用這個。 – Kyle 2012-03-16 04:27:20
@凱爾:謝謝。 'Regexp.union'可以比使用手工構建一個大的替換正則表達式更好用。 – 2012-03-16 04:33:53
再次感謝@ muistooshort! – 2012-03-16 15:29:26