regex intermediate

How to use the /x modifier for readable regex

Question

How can I make complex regular expressions more readable in Perl?

The /x modifier allows whitespace and comments in regex patterns:

use strict;
use warnings;

my $email = 'user@example.com';

# Without /x (hard to read)
if ($email =~ /^([a-zA-Z0-9._%+-]+)@([a-zA-Z0-9.-]+)\.([a-zA-Z]{2,})$/) {
    print "Valid email\n";
}

# With /x (readable)
if ($email =~ /
    ^                      # Start of string
    ([a-zA-Z0-9._%+-]+)   # Local part
    @                      # At symbol
    ([a-zA-Z0-9.-]+)      # Domain name
    \.                     # Dot (escaped)
    ([a-zA-Z]{2,})        # TLD (2+ letters)
    $                      # End of string
/x) {
    print "Valid: local=$1, domain=$2, tld=$3\n";
}

Use /x for complex patterns. To match literal spaces, use \ or \s.

Was this helpful?

Related Questions