Skip to content

Instantly share code, notes, and snippets.

@maripiyoko
Last active August 29, 2015 14:04
Show Gist options
  • Save maripiyoko/bfddbf1e821183b3fbe2 to your computer and use it in GitHub Desktop.
Save maripiyoko/bfddbf1e821183b3fbe2 to your computer and use it in GitHub Desktop.
Ruby RegEx Practice.
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]}"
@maripiyoko
Copy link
Author

Ruby 正規表現の練習
かっこの中にあるターゲットの単語の個数を調べる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment