Last active
August 29, 2015 14:04
-
-
Save maripiyoko/bfddbf1e821183b3fbe2 to your computer and use it in GitHub Desktop.
Ruby RegEx Practice.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
input = "(apple banana) [()mellon orange {banana}] (apple apple {mellon orange})" | |
# split input text by (), {}, [] | |
re_matchers = [ /\(.*?\)/, /\{.*?\}/, /\[.*?\]/ ] | |
results = [] | |
re_matchers.each do |re| | |
results.concat(input.scan(re)) | |
end | |
# count target occurrence | |
re_targets = /apple|banana|mellon|orange/ | |
result_hash = Hash.new | |
results.each do |text| | |
count = text.scan(re_targets).size | |
puts "\t#{text} => #{count}" | |
result_hash[text] = count | |
end | |
# max | |
max_val = result_hash.max {|k,v| k[1] <=> v[1]} | |
puts "answer=#{max_val[1]} text=#{max_val[0]}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby 正規表現の練習
かっこの中にあるターゲットの単語の個数を調べる