Creating and Using Regular Expressions
Ruby has many ways of creating a regular expression pattern. By far, the most common is to write the pattern between forward slashes. Thus, the pattern /cat/ is a regular expression literal in the same way that "cat" is a string literal.
/cat/ is an example of a simple pattern. It matches any string that contains the substring cat. In fact, inside a regular expression pattern, all characters except ., |, (, ), [, ], {, }, +, \, ^, $, *, and ? match themselves. So, at the risk of creating something that sounds like a logic puzzle, here are some patterns and examples of strings they match and don’t match:
|
/cat/ |
Matches "dog and cat" and "catch" but not "Cat" or "c.a.t." |
|
/123/ |
Matches "86512312" and |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access