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