Created
November 6, 2009 11:50
-
-
Save gongo/227953 to your computer and use it in GitHub Desktop.
カンマ(,)による複数、及びハイフン(-)による連続した数字の取得
This file contains hidden or 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
#!/usr/bin/env ruby | |
unless ARGV[0] | |
puts <<EOS | |
Usage: | |
ruby parse_volume.rb NUM | |
Example: | |
./parse_volume 12-15,19,23-29 | |
#=> 12 13 14 15 19 23 24 25 26 27 28 29 | |
EOS | |
exit | |
end | |
str = ARGV[0].gsub(/\s/, "") | |
vol = Array.new | |
if /^(?!^[^\d])(?!.*[^\d]$)(?!.*\,-)(?!.*-\,)(?!.*--)[-\,\d]*$/ =~ str | |
str.split(',').each do |s| | |
next if s.empty? | |
pair = s.split('-') | |
if pair.length > 1 # ex. a = "3-6" => (3..6).to_a | |
vol.concat((pair[0].to_i..pair[1].to_i).to_a) | |
else | |
vol << pair[0].to_i | |
end | |
end | |
vol.uniq! | |
vol.sort! | |
puts vol.join(' ') | |
else | |
puts "Can't parse '#{str}'" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment