Switches

A regular expression can be followed by one or more switches, which are single-letter flags that modify how the regex is interpreted. There are several switches available, but only three that we'll concern ourselves with here. They can be used individually or in combination.

Case Insensitivity: /i

Just as any good text editor supports case-insensitive searching, Ruby supports case-insensitive pattern matching.

/APEX/  =~ "apex" #-> nil
/APEX/i =~ "apex" #-> 0

/^(\b\w+\b).*\1$/  =~ "Time after time" #-> nil
/^(\b\w+\b).*\1$/i =~ "Time after time" #-> 0

Extended Legibility: /x

It isn't often used, but the /x switch lets you embed comments and spacing in a regular expression. You might find /\b\w{1,4}\b\W*/ more readable in this form:

Get Sams Teach Yourself Ruby in 21 Days 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.