matchdata-highlight

A small gem that adds a highlight method to regex match results (Ruby’s MatchData). It returns a string with marker strings inserted around the matched portion. If you omit the markers, ANSI escape sequences from term/ansicolor are used, so the match shows up in red in the terminal.

The library itself is a single file of about 40 lines, with usage examples left as comments at the end of the source.

puts "foobar foobar BAZ".match(/(foobar)/).highlight
puts /foobar/.match("foobar foobar BAZ").highlight("<B>", "</B>")
puts /foobar/.highlight("foobar foobar BAZ")
puts /foobar/.highlight("foobar foobar BAZ", :begin => '<B>', :end => '</B>')
puts /foobar/.highlight("foobar foobar BAZ", '<B>', '</B>')

Internals

It consists of nothing but monkey patches to two classes, MatchData and Regexp. Here is the processing flow.

Processing flow diagram of matchdata-highlight