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


