Computer Science Canada [Regex-tut] A gentle introduction |
Author: | wtd [ Sat Nov 13, 2004 9:05 pm ] | ||||||||||||||||||
Post subject: | [Regex-tut] A gentle introduction | ||||||||||||||||||
Prerequisites Install Ruby, if you haven't already. 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:
Is:
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.
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:
Doesn't have to match the entire string. In fact...
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:
The caret at the beginning of the regex says, "start searching at the beginning of the string." To indicate the end of the string:
And of course, combine them:
And the pattern will only match:
|