Sunday, July 31, 2011

Extensions in perl

Extensions significantly add to the power of regular expressions instead of adding lot of metacharacters.

Commonly used extensions in perl are:
1)(?#TEXT)    - it is used for adding comments in the regular expressions.

2)(?:...)       - it is used in case when you want paranthesis to be used without saving
the matched pattern in $n

3)(?=...)    -  it is used for matching without using the specific value in the $& variable.

4)(?!...)  - it is used when you don't want the pattern in the paranthesis to follow the word before or after.

Example:
1)(?#TEXT)-
it can be used simply used it just adds a clarity to the people viewing this pattern.
$dd =~ m/\w(?#it matches a single character)\s(it matches a single character)/;

2)(?:.....)-


$dd="hello how are you";
$dd=~ m/(?:\w*)/;
print $1;

if you see the example above the $1 is supposed to match hello since "?:" is specified in parantheses it is empty.

3)(?=...)-
it can be used in the case when you want to match a pattern based on the value in the paranthesis but it should not get included in $& variable in that case this will be useful.

$dd="hello how are you";
$dd=~ m/\w*\s+(?=how)/;
print $&;

Output:
hello

In the example specified i am trying to match a word followed by "how".If i have
parathesis without "?=" the output will be "hello how".Using "?=" has done the trick to print only hello.

4)(?!....)
It is very useful extension which can be used in case where you donot want a word to follow or precede the match you are looking for.
For example: m/red(?!carpet)/ will match redsea or redfly but not redcarpet.
The detailed example can be seen in the url:
http://linux-forum-karthik.blogspot.com/2011/07/to-match-pattern-not-having-word.html



No comments:

Post a Comment