Chapter 9 Regular Expressions
Ruby supports a built-in regular expressions feature. Regular expressions are strings that describe or match a set of other strings.
Regular expressions are written in the form of /pattern/modifiers. “Pattern” represents the regular expression itself while the “modifiers” refer to sets of characters indicating various options.
The following lists the components included in a regular expression:
- Literal Characters – Any literal character included in a regular expression matches itself in the string.
Example:
/c/
Ruby contains special characters such as ^, $, ?, ., /, \, [, ], {, }, (, ), +, and so forth. When you match one of these characters in a string, escape it with a backslash (\).
Example:
/\?/
* Wildcard character (.) – To match any character at some point in the pattern, use a special wildcard character. The wildcard character (.) matches any character with the exception of a newline.
Example:
/.ave/
The above regular expression matches “gave” or “save”. It even matches “%ave” or “2ave”.
- Character class – This refers to a list of characters which is placed inside a regular expression.
Example:
/[ gs] ave/
The above example shows that the regular expression matches either g or s, followed by ave. The expression only matches either “gave” or “save”.
A character class allows regular expressions to have multiple possible characters, but with a limited number of them.


