Perl | Assertions in Regex
Regular Expression (Regex or RE) in Perl is when a special string describing a sequence or the search pattern in the given string.
An Assertion in Regular Expression is when a match is possible in some way. The Perl’s regex engine evaluates the given string from left to right, searching for the match of the sequence, and when we found the match sequence at a given point in a string that position is called as match position or current match position. The Look Around Assertions facilitates us to match a pattern or a string before or after the match position or current match position without changing the current match position.
Types of Assertions:
There are mainly two types of Assertions in Regex which are further divided:
- Lookahead Assertions: In this type of assertion we look ahead the current match position, means will search the string after the current match position or the pattern/string succeeding string, without moving the current match position.
Syntax for Lookahead Assertions:
/(?=pattern)/
Lookahead Assertions can be further classified into:
- Positive Lookahead(?=pattern): Positive Lookahead is just like the normal Lookahead assertion, it makes sure that the pattern does exist in the given string which we are matching.
Example:
use strict;
use warnings;
$_ = "chicken cake" ;
s/chicken (?=cake)/chocolate /;
print $_ ;
|
Output:
chocolate cake
- Negative Lookahead(?!pattern): In Negative Lookahead, it Lookaheads the pattern and makes sure that the pattern doesnot exist in the given string which we are matching. To make Lookahead assertion as Negative Lookahead we just replace the ‘='(Equal) with ‘!'(Exclamation).
Example:
use strict;
use warnings;
$_ = "chicken cake" ;
s/chicken (?!curry)/chocolate /;
print $_ ;
|
Output:
chocolate cake
- Lookbehind Assertions: In this type of assertion we look behind the current match position, means will search the string before the current match position or the preceding string, without moving the current match position.
Syntax for Lookbehind Assertions:
/(?<=pattern)/
Lookbehind Assertions can be further classified into:
- Positive Lookbehind(?<=pattern):Positive Lookbehind, it makes sure that the pattern does exist in the given string we are matching.
Example:
use strict;
use warnings;
$_ = "chocolate curry" ;
s/(?<=chocolate )curry/cake /;
print $_ ;
|
Output:
chocolate cake
- Negative Lookbehind(?<!pattern):Negative Lookbehind, it Lookbehind the pattern and make sure that the pattern does not exist in the given string we are matching. To make Lookbehind assertion as negative we just replace the ‘='(Equal) with ‘!'(Exclamation).
Example:
use strict;
use warnings;
$_ = "chocolate curry" ;
s/(?<!chicken )curry/cake /;
print $_ ;
|
Output:
chocolate cake
Last Updated :
09 Sep, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...