The most likely place that you’re going to use regular expressions
in Rails is the validates_format_of
method demonstrated
in Chapter 7, which is
shown here as Example C-1.
Example C-1. Validating data against regular expressions
# ensure secret contains at least one number validates_format_of :secret,:with => /[0-9]/
, :message => "must contain at least one number" # ensure secret contains at least one upper case validates_format_of :secret,:with => /[A-Z]/
, :message => "must contain at least one upper case character" # ensure secret contains at least one lower case validates_format_of :secret,:with => /[a-z]/
, :message => "must contain at least one lower case character"
These samples all use regular expressions in their simplest
typical use case: testing to see whether a string contains a pattern.
Each of these will test :secret
against the expression specified by :with
. If the pattern in :with
matches, then validation passes. If not,
then validation fails and the :message
will be returned. Removing the Rails
trim, the first of these could be stated roughly in Ruby as:
if :secret =~
/[0-9]/
#yes, it's there
else
#no, it's not
end
The =~
is Ruby’s way of
declaring that the test is going to compare the contents of the left
operand against the regular expression on the right side. It doesn’t
actually return true
or false
, though—it returns the numeric position
at which the first match begins, if there is a match, and nil
if there are none. You can treat it as a
boolean evaluator, however, because nil
always behaves as false
in a boolean evaluation, and other
non-false
values are the same as
true
.
There isn’t room here to explain them, but if you need to do
more with regular expressions than just testing whether there’s a
match, you’ll be interested in the $~
variable (or Regexp.last_match
), which gives you access
to more detail on the results of the matching. A variety of methods on
the String
object, notably sub
, gsub
, and slice
, also use regular expressions for
slicing and dicing. You can also retrieve match results with $1
for the first match, $2
for the second, and so on, variables
created by the match.
There’s one other feature in these simple examples worth a little
more depth. Reading them, you might have thought that /[0-9]/
was a regular expression. It’s a
regular expression object, but the expression itself is [0-9]
. Ruby uses the forward slash as a
delimiter for regular expressions, much like quotes are used for
strings. Unlike strings, though, you can add flags after the closing
slash, as you’ll see later.
If you’d prefer, you can also use Regexp.new
to create regular expression
objects. (This usually makes sense if your code needs to meet changing
circumstances on the fly at runtime.)