liveBook · Manning

Regular expression literal

As explained in The Well-Grounded Rubyist, Fourth Edition

A regexp literal is Ruby syntax that directly represents a regular expression between delimiters, optionally followed by modifiers.

A regular expression literal is Ruby syntax for creating a Regexp object directly. The usual form places a pattern between forward slashes, such as /abc/; %r{} and other paired delimiters provide an alternative notation. section 11.2.2

Ruby regular expression literals support several closely related operations:

  • Use match? for a Boolean result: /abc/.match?("The alphabet starts with abc.") returns true. section 11.2.2
  • Use match to receive MatchData when a pattern succeeds, or nil when it fails. section 11.2.2
  • Use =~ between a string and a regexp; a successful match returns the match position. section 11.2.2
  • Append modifiers such as i, m, or x to alter matching behavior; x permits spaced, commented multiline patterns when whitespace is escaped where literal. section 11.5.4

Matching a literal pattern

pattern = /abc/ text = "The alphabet starts with abc." pattern.match?(text) # true pattern.match(text) # #<MatchData "abc"> text =~ pattern # 25 section 11.2.2

/
 \((\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

A multiline phone-number regexp demonstrates the x modifier, comments, grouping, repetition, and escaped literal delimiters. section 11.5.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains slash and percent delimiters, matching results, and modifiers, but defers exhaustive regular-expression syntax.
Examples
Uses /abc/, %r{} and %r(abc)i, multiline phone-number patterns, and collections-report extraction exercises.
What it assumes
Assumes strings and basic method calls while introducing Regexp construction and the relationship between patterns and strings.
What you can do after
Apply it via Ruby to test strings, obtain match positions or MatchData, and format complex patterns with modifiers.
How it connects
Connects Regexp literals to String, MatchData, pattern matching, and regular-expression modifiers.

Also explained in

Compare how 3 books explain regular expression literal →

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.