Perl | Regular Expressions
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:
# Perl program to demonstrate
# the m// and =~ operators
# Actual String
$a
=
"GEEKSFORGEEKS"
;
# Prints match found if
# its found in $a
if
(
$a
=~ m[GEEKS])
{
print
"Match Found\n"
;
}
# Prints match not found
# if its not found in $a
else
{
print
"Match Not Found\n"
;
}
Output:Match Found
- Program 2: To illustrate the use of ‘m//’ and ‘!~’ as follows:
# Perl program to demonstrate
# the m// and !~ operators
# Actual String
$a
=
"GEEKSFORGEEKS"
;
# Prints match found if
# its not found in $a
if
(
$a
!~ m[GEEKS])
{
print
"Match Found\n"
;
}
# Prints match not found
# if it is found in $a
else
{
print
"Match Not Found\n"
;
}
Output:Match Not Found
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.
Please Login to comment...