简体   繁体   中英

Matching Portions of A String to Elements of an Array in Ruby

I have a string & an array, and am trying to iterate through the array to see of any of its elements match a portion of the string.

string = "HOPJYJKCONNECTICUTQZIDAHOKR"

states_array = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]

How can I iterate overs the states_array so that I can find all matches in the string? I would want to output all the matched states as an array & so the final result might look like:

#=> ["CONNECTICUT", "IDAHO"]
string = "HOPJYJKCONNECTICUTQZIDAHOKR"
states = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]

states.select { |s| string[s] }
# => ["IDAHO", "CONNECTICUT"]

Matt的不错解决方案,但也可以做到

states.select { |s| string.match(s)}

Since you specified the regex tag on this question, you could do with with a regex as follows:

string.scan(Regexp.new(states.join('|')))
# => ["CONNECTICUT", "IDAHO"] 

using the variables in Matt's answer. Not recommending this, however. :-)

This is like @Peter_Alvin's answer,using the built in method union .

states_array = ["TEXAS", "ALASKA", "IDAHO", "FLORIDA", "MONTANA", "OHIO", "NEWMEXICO", "CONNECTICUT", "COLORADO"]
str = "HOPJYJKCONNECTICUTQZIDAHOKR"
p str.scan(Regexp.union(states_array)) # ["CONNECTICUT", "IDAHO"]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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