Regular Expressions

Lesson 18 of 20

Patterns in slashes: find where text fits with =~, harvest every match with scan, and rewrite strings with sub and gsub.

The big picture

A pattern language inside the language

A regex like /c.t/ is a tiny search recipe: Ruby slides it across a string and reports every place it fits.

Regexes Are Literal

Write patterns between slashes: /cat/, /\d+/, /^hi/ — they are Regex objects.

=~ Finds the Spot

text =~ /pattern/ returns the index of the first match, or nil when nothing fits.

scan Collects All

text.scan(/pattern/) gathers every match into an array.

sub and gsub Rewrite

sub replaces the first match; gsub replaces every one of them.