Thursday, January 27, 2011

Types of Lookaround and examples

4 Types of Lookaround
Positive Lookbehind (?<=......) successful if can match to the left
Negative Lookbehind (?<!......) successful if can not match to the left
Positive Lookahead (?=......) successful if can match to the right
Negative Lookahead (?!......) successful if can not match to the right

Examples
$string = "Jeffery is a boy that start with Jeffs";
$string =~ s/\bJeff(?=s\b)/Jeff'/g;
=> The results is : Jeffery is a boy that start with Jeff's

$string = "Jefferry Tomson";
$string =~ s/(?=Jefferry)Jeff/J/; #case 1
$string =~ s/Jeff(?=erry)/J/; # case 2
=> For both cases the Result is : Jerry Tomson



$text = "The numbers are 298444215 and 123234567";
$text =~ s/(?<=\d)(?=(\d\d\d)+(?!\w))/,/g; # case 1
$text =~ s/(?<=\d)(?=(\d\d\d)+(?!\d))/,/g; # case 2
$text =~ s/(\d)(?=(\d\d\d)+(?!\d))/$1,/g;#case 3
=> For all cases the result is : The numbers are 298,444,215 and 123,234,567



$text = "The numbers are 298444215 and 123234567";
$text =~ s/(\d)((\d\d\d)+\b)/$1,$2/g;#no look behind and no lookahead
print $text;#result The numbers are 298,444215 and 123,234567

To have the result : The numbers are 298,444,215 and 123,234,567 we have to do the following:
$text = "The numbers are 298444215 and 123234567";
while ($text =~ s/(\d)((\d\d\d)+\b)/$1,$2/g)
{}

No comments:

Post a Comment