The program requires input twice, once for a string and once for a regular expression. The string is tested against the regular expression, then displayed with all the matching parts highlighted in reverse video.
#!/usr/local/bin/ruby
# The program requires input twice, once for a string and
# once for a regular expression. The string is tested against
# the regular expression, then displayed with all the
# matching parts highlighted in reverse video.
# http://www.rubyist.net/~slagell/ruby/regexp.html
st = "\033[7m" # makes the reverse video
en = "\033[m" # undoes the reverse video
puts "#{st} #{en}"
puts "Enter an empty string at any time to exit."
while true
print "str> "; STDOUT.flush; str = gets.chop
break if str.empty?
print "pat> "; STDOUT.flush; pat = gets.chop
break if pat.empty?
re = Regexp.new(pat)
puts str.gsub(re,"#{st}\\&#{en}") # gsub is a global
# substitution, all matches are substituted
# rather than just the first.
end