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 ...

Get Text Processing with Ruby now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.