Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Regex-tut] A gentle introduction
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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:

code:
"Hello, world!"


Is:

code:
/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.

code:
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:

code:
/Hello, world!/


Doesn't have to match the entire string. In fact...

code:
"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:

code:
/^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:

code:
/Hello, world!$/


And of course, combine them:

code:
/^Hello, world!$/


And the pattern will only match:

code:
"Hello, world!"
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: