I recently discovered a feature of regular expressions called lookahead. This means for a match the lookahead must exist but it does not become part of the matched string. NB: (group) print first group with \1

"123456".gsub(/(\d\d\d)/, '\1,')

Now with lookahead

"123456".gsub(/(\d\d\d)(?=\d)/, '\1,')

There are 2 types of lookahead

match (?=x)
not-match (?!x)

Ruby 1.8.x does not support these by default but by using Oniguruma which is the default regex engine in Ruby 1.9.x you can also use lookbehind expressions.

match (?<=x)
not-match (?<!x)

Example not using lookbehind


With Not lookbehind


More info on Lookarounds