Home arrow Perl Programming arrow Perl Regular Expressions
Perl Regular Expressions PDF  
Digg Reddit Stumble Upon Facebook Twitter Google Technorati Bookmark
Thursday, 05 June 2008
This tutorial is also available for download as PDF document
Learn Perl by Example - Perl Handbook for Beginners - Basics of Perl Scripting - Perl Regular Expressions.

Searching for a string
------------------------------

#!/usr/bin/perl -w

$exp = "This is a string";

if ($exp =~ /This/) {
        print ("String Matches!\n");
}


Searching for a string using case insensitive
--------------------------------------------------------------

#!/usr/bin/perl -w

$exp = "This is a string";

if ($exp =~ /tHis/i) {
        print ("String Matches!\n");
}


Searching for a digit
----------------------------

#!/usr/bin/perl -w

$exp = "This is 8 string";

if ($exp =~ /\d/) {
        print ("String Matches!\n");
}

Searching for 2 digits
-----------------------------

#!/usr/bin/perl -w

$exp = "This is 88 string";

if ($exp =~ /\d\d/) {
        print ("String Matches!\n");
}


Searching for whitespaces
-------------------------------------

#!/usr/bin/perl -w

$exp = "This is string";

if ($exp =~ /\s/) {
        print ("String Matches!\n");
}


Searching for a string that begins with a pattern
----------------------------------------------------------

#!/usr/bin/perl -w

$exp = "This is string";

if ($exp =~ /^This/) {
        print ("String Matches!\n");
}


Searching for a string that ends with a pattern
----------------------------------------------------------------

#!/usr/bin/perl -w

$exp = "This is string";

if ($exp =~ /string$/) {
        print ("String Matches!\n");
}


Search for a digit with white space in front and after it.
--------------------------------------------------------------------------

#!/usr/bin/perl -w

$exp = "This 1 is string";

if ($exp =~ /\s\d\s/) {
        print ("String Matches!\n");
}


Search for a blank line
------------------------------

This is usefull  to check for blank lines in a file. For that, instead of $exp variable you will need an array that will contain every line from that file.

#!/usr/bin/perl -w

$exp = "";

if ($exp =~ /^$/) {
        print ("String Matches!\n");

Replace a pattern
------------------------


#!/usr/bin/perl -w

$exp = "This is a string";

if ($exp =~ s/This is/Test/) {
        print ("$exp\n");
}
Last Updated ( Thursday, 05 June 2008 )
 
Next >

Misc

Linux Tips

Polls

What is your favorite Linux Distribution ? (we just added Mint and reset the pool data)