liveBook · Manning

Regular expression flag

As explained in The Well-Grounded Rubyist, Fourth Edition

A regexp modifier is a letter appended to a Ruby regular-expression literal that changes how matching or parsing behaves.

A regular expression flag is a letter placed after the closing slash of a Ruby regexp literal. It switches matching or parsing behavior without changing the main pattern. section 11.5.4

Ruby flags provide several practical controls:

  • Use i for case-insensitive matching, as in /abc/i. section 11.5.4
  • Use m to make the wildcard dot match newline characters as well as other characters. This lets a pattern span multiple lines. section 11.5.4
  • Use x to ignore unescaped whitespace in the pattern, making room for line breaks and comments. Escape a space when it must remain literal. section 11.5.4
  • Place flags after the complete expression when using the %r(...) regexp-literal form, as in %r(abc)i. section 11.5.4

Matching across newlines

Given a string containing text between parentheses on three lines, /\(.*?\)/m.match(str) can capture the complete parenthesized span. Without m, the dot stops at the first newline and the match fails before finding the closing parenthesis. section 11.5.4

/
 \((\d{3})\)  # 3 digits inside literal parens (area code)
   \s         # One space character
 (\d{3})      # 3 digits (exchange)
    -         # Hyphen
 (\d{4})      # 4 digits (second part of number
/x

An expanded phone-number regexp demonstrates how x supports indentation, line breaks, and comments while preserving escaped literal spaces. section 11.5.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines modifier placement and explains i, m, and x through runnable contrasts, warnings, and multiline examples.
Examples
Uses /abc/i, a multiline parenthesis pattern, an expanded phone-number regexp, and %r(abc)i.
What it assumes
Assumes basic Ruby regexp literals and match operations while building on quantifiers, anchors, and wildcard behavior.
What you can do after
Apply it via Ruby regexp literals to control case sensitivity, newline matching, and readable pattern layout.
How it connects
Connects modifiers with quantifiers, anchors, wildcard matching, regexp literals, and match operations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.