regex advanced
How to use lookahead and lookbehind in Perl regex
Question
How do I use positive and negative lookahead/lookbehind assertions in Perl?
Lookahead and lookbehind assertions check conditions without consuming characters:
use strict;
use warnings;
my $text = "Password123";
# Positive lookahead (?=...): assert next chars match
if ($text =~ /^(?=.*[A-Z])(?=.*[0-9]).{8,}$/) {
print "Valid: has uppercase and digit, 8+ chars\n";
}
# Negative lookahead (?!...): assert next chars don't match
my $safe = "myfile.txt";
if ($safe =~ /^(?!.*\.\.\/).*$/) {
print "Safe: no directory traversal\n";
}
# Positive lookbehind (?<=...): assert previous chars match
my $price = "USD100";
if ($price =~ /(?<=USD)\d+/) {
print "Amount: $&\n"; # 100
}
# Negative lookbehind (?
Lookbehind assertions must be fixed-width in most Perl versions. Use lookahead/lookbehind for complex validation without capturing.
Was this helpful?
Related Questions
- How to validate email addresses using Perl regex?
- How to split a string by regex pattern in Perl?
- How to use greedy vs non-greedy quantifiers in Perl regex?
- How to match start and end of string with ^ and $ in Perl?
- How to use alternation | in Perl regex?
- How to use the qr// operator to compile regex in Perl?