Tuesday, March 10, 2009

Perl: Multiline Search Replace using regex (/m /s)

Perl multiple line search replacement using regular expression.

Here is what you need to do when you have data on multiple lines, and you need to perform regular expression matching. At the below regular expression, I have used /ims three modifiers. This will enable you to match regex over multiple lines with case in-sensitive always.

## matcing multi line string at Perl
my $string = "perl multi line <Tag> \n 10 \n </taG> search replace";
if( $string =~ /<tag>(.*?)<\/tag>/ims ){
print "$1\n";

To replace over multiple line, once again same, just use /ims three modifiers. If you need to replace more than one matching, that case add /g too.

## replacing multiline string at perl
$string =~ s/<tag>.*?<\/tag>/<Done>/ims;
print "$string\n";

Share your experience about this issue. All are welcome to post comments. Thanks once again for reading the post.

No comments:

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...