
-----------------------------------
wtd
Sat Nov 13, 2004 9:05 pm

[Regex-tut] A gentle introduction
-----------------------------------
Prerequisites

Install What does a regular expression look like?

Ruby gives us a very light syntax for defining regular expressions.  A simple regular expression to match the string:

"Hello, world!"

Is:

/Hello, world!/

How do you actually test to see if there's a match?

The =~ operator permits us to test a string against a regular expression, or vice versa.  The =~ operator is commutative.  

if "Hello, world!" =~ /Hello, world!/
   puts "It matched!"
else
   puts "It didn't match."
end

That's all well and good, but...

... so far we've only been dealing with a static pattern.  Or have we?

A regular expression such as:

/Hello, world!/

Doesn't have to match the entire string.  In fact...

"foo Hello, world! bar"

Would match that regular expression.  Now, maybe that's good enough.  But maybe it isn't.  To match from the beginning of a string, use:

/^Hello, world!/

The caret at the beginning of the regex says, "start searching at the beginning of the string."  To indicate the end of the string:

/Hello, world!$/

And of course, combine them:

/^Hello, world!$/

And the pattern will only match:

"Hello, world!"
