O'Reilly logo

Text Processing with Ruby by Rob Miller

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Transforming Text

We’ve dealt with merely matching patterns in text, but that’s only half of what regular expressions can do. We can also use them to perform substitutions, transforming text that matches patterns into something else entirely.

We can do this in fairly simple ways, replacing a pattern with a fixed string. Or we can do more complex replacements, using capture groups to include information from the pattern we’re matching in the replacement.

Two methods are used to perform the majority of regex-based substitutions in Ruby. Let’s look at them next.

sub and gsub

Even if you’re not familiar with regular expressions, you might have used the sub and gsubsubstitute and global substitute—methods to perform replacements on text.

Both methods ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required