Regexes are complex enough on their own, but also have a few specific rules for using them in Ruby.
Making a Regular Expression #
Put it in forward slashes.
Testing a Regular Expression #
=- operator to return a boolean if the string matches the expression.
/[0-9a-f]/ =- '9' # 0 (it matched once)
/[0-9a-f]/ =- 'ae49' # 3 (it matched three times)
/[0-9a-f]/ =- 'g' # nil (no matches)
Since matches return an integer and misses return
nil, you can treat them as booleans if you want to.
Make it Case Insensitive #
i to the end of it.
/[0-9a-f]/ =- 'A' # nil
/[0-9a-f]/i =- 'A' # 0
Use it With .gsub #
You can use regexes with
gsub so any matching substrings are replaced with something else.
noHexChars = 'abcdefghij'.gsub(/[0-9a-f]/, '*')
Checking in Specific Parts of a String #
\Ato only register matches at the start of a string.
^to include the start of all lines in multiline strings.
\zfor the same but with the end of a string.
$to include the end of all lines in multiline strings.
By default, dots don't match the end of a newline character. You can include it by using
m at the end of the regex.
/^Once upon a time.*happily ever after\.$/m