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
- 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?