Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and ‘!~‘ (Negated Regex Operator) are used. Before moving to Binding operators let’s have a look at building patterns.
Building Patterns: In Perl, patterns can be constructed using the m// operator. In this operator, the required pattern is simply placed between the two slashes and the binding operators are used to search for the pattern in the specified string.
Using m// and Binding Operators: Mostly the binding operators are used with the m// operator so that required pattern could be matched out. Regex operator is used to match a string with a regular expression. The left-hand side of the statement will contain a string which will be matched with the right-hand side containing the specified pattern. Negated regex operator is used to check if the string is not equal to the regular expression specified on the right-hand side.
- Program 1: To illustrate the use of ‘m//’ and ‘=~’ as follows:
$a = "GEEKSFORGEEKS" ;
if ( $a =~ m[GEEKS])
{
print "Match Found\n" ;
}
else
{
print "Match Not Found\n" ;
}
|
- Program 2: To illustrate the use of ‘m//’ and ‘!~’ as follows:
$a = "GEEKSFORGEEKS" ;
if ( $a !~ m[GEEKS])
{
print "Match Found\n" ;
}
else
{
print "Match Not Found\n" ;
}
|
Uses of Regular Expression:
- It can be used to count the number of occurrence of a specified pattern in a string.
- It can be used to search for a string which matches the specified pattern.
- It can also replace the searched pattern with some other specified string.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
30 May, 2019
Like Article
Save Article