Friday, July 25, 2008

Regular Expressions (more)

There are many more options that can be used with PERL regular expressions.

The different options that I have used are: g,i,s,m,o,x
These options are to be specified like this:
/reg-exp/options
One or more options can be used, but one cant' use s & m simultaneously.

So here are the meanings of these regular expressions ...

g -> Match Globally:
This option can be used when you are trying to match a pattern in the whole string. As in this example :
$you_appeared++ while(/\s+you\s+/g);

i -> Ignore Case:
Use this when case of the pattern does not matter.

s -> Treat Workspace As Single Line:
This option is used when you need to match "\n" with reg-exp special character '.'. Or put simple, you this option when the work space has "\n"'s and you want to match something considering "\n".
my $workspace = "I'am sure you are confused\nYou have to use it to understand it\n";
if ($workspace =~ /use/s) {
print "$&$'\n";
}

m -> Treat workspace as multiple lines. This option differs from above, here '.' does not match a "\n" however, treats workspace as multiple lines.

o -> compile the pattern once. The effect this produces is visible when you use a variable. Since the pattern is compiled only once, the variable will be replaced only once in the pattern - no matter how many times the pattern is used.

x -> add comments inside the regexp, using '#'


0 comments: