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
