# # # # # # # # #
# /45/regexp_visualize.rb
#
# by               Jan Lelis
# e-mail:          mail@janlelis.de
# type/version:    ruby 
# snippet url:     http://rbJL.net/45/regexp_visualize.rb
# original post:   http://rbJL.net/45-small-ruby-cli-improvements-part-1-command-line-regex-debugging
# license:         CC-BY (DE)
#
# (c) 2011 Jan Lelis.

class Regexp
  def visualize(string, groups = nil)
    if self =~ string
      if !groups
        puts $` + ' >' + $& + '< ' + $'
      else
        Array( groups ).each{ |group|
          begin
            gr_string = string.dup
            gr_string[ $~.end( group ),   0 ] = '< '
            gr_string[ $~.begin( group ), 0 ] = ' >'
            puts group.to_s + ': ' + gr_string
          rescue IndexError
            puts group.to_s + ': no match'
          end
        }
      end
    else
      puts 'no match'
    end

    nil
  end

  alias vis visualize
end