Regular Expression Patterns
Like most things in Ruby, regular expressions are just objects—they are instances of the class Regexp. This means you can assign them to variables, pass them to methods, and so on:
| str = "dog and cat" |
| pattern = /nd/ |
| pattern.match?(str) # => true |
| str.match?(pattern) # => true |
You can also create regular expression objects by calling the Regexp class’s new method or by using the arbitrary delimiter %r{...} syntax. The %r syntax is particularly useful when creating patterns that contain forward slashes:
| /mm\/dd/ # => /mm\/dd/ |
| Regexp.new("mm/dd") # => /mm\/dd/ |
| %r{mm/dd} # => /mm\/dd/ |
Get Programming Ruby 3.3 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.