ZetCode

Perl parsing with regular expressions

last modified November 25, 2026 Perl 5.44

Regular expressions are Perl's main tool for extracting structure from text. This article puts together the features from the previous regex articles, such as captures, named groups, the /x modifier and global matching, and applies them to practical tasks: configuration files, server logs, URLs, CSV lines and input validation. The examples start with a single line and grow into small parsers.

Parsing a key and a value

Many text formats consist of lines with a name, an equals sign and a value. A single pattern with two capture groups splits such a line.

keyvalue.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $line = 'timeout = 30   ';

if ($line =~ /^\s*(\w+)\s*=\s*(.*?)\s*$/) {
    say "key:   '$1'";
    say "value: '$2'";
}

The first group captures the key, a run of word characters. The spaces around the equals sign are matched by \s* outside the groups, so they are not part of the result. The lazy (.*?) followed by \s*$ leaves the trailing spaces out of the value. The quotes in the output show where each value begins and ends.

$ perl keyvalue.pl
key:   'timeout'
value: '30'

Parsing a settings file

A real file has many such lines, together with comments and blank lines. The program removes the comments first and then applies the pattern from the previous section to each line.

settings.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $text = <<~'END';
    # connection settings
    host = example.com
    port = 8080

    timeout = 30   # seconds
    END

my %conf;

for my $line (split /\n/, $text) {
    $line =~ s/\s*#.*//;
    next unless $line =~ /^\s*(\w+)\s*=\s*(.*?)\s*$/;
    $conf{$1} = $2;
}

for my $key (sort keys %conf) {
    say "$key => '$conf{$key}'";
}

The text is split into lines at the newlines. The substitution s/\s*#.*// deletes a comment together with the spaces before it, whether it fills the whole line or follows a setting. Lines that do not match the pattern, such as the empty ones, are skipped, and the others are stored in a hash.

$ perl settings.pl
host => 'example.com'
port => '8080'
timeout => '30'

Parsing a log line

Web server logs have more fields, and a pattern with many numbered groups becomes hard to read. Named groups and the /x modifier make the pattern document itself.

log_line.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $line = '192.168.1.5 - - [25/Nov/2026:10:15:32 +0000] '
    . '"GET /index.html HTTP/1.1" 200 5120';

my $log_re = qr/
    ^ (?<ip> \S+ ) \s+ \S+ \s+ (?<user> \S+ ) \s+
    \[ (?<time> [^\]]+ ) \] \s+
    " (?<method> [A-Z]+ ) \s+ (?<path> \S+ ) \s+ [^"]* " \s+
    (?<status> \d{3} ) \s+ (?<bytes> \d+ ) $
/x;

if ($line =~ $log_re) {
    for my $field (qw(ip user time method path status bytes)) {
        printf "%-7s %s\n", $field, $+{$field};
    }
}

The pattern follows the common log format: client address, identity, user, time in brackets, the request in quotes, status code and size. Each field has its own named group, and the values are read from the %+ hash. Fields we do not need, such as the identity and the protocol, are matched without a group.

$ perl log_line.pl
ip      192.168.1.5
user    -
time    25/Nov/2026:10:15:32 +0000
method  GET
path    /index.html
status  200
bytes   5120

Summarizing a log

With a working line pattern, a log file can be summarized in a few lines of code. The program counts requests by status, finds the number of distinct clients and adds up the transferred bytes.

log_summary.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $log = <<~'END';
    192.168.1.5 - - [25/Nov/2026:10:15:32 +0000] "GET /index.html HTTP/1.1" 200 5120
    10.0.0.7 - lucia [25/Nov/2026:10:16:01 +0000] "POST /login HTTP/1.1" 302 0
    192.168.1.5 - - [25/Nov/2026:10:17:45 +0000] "GET /missing HTTP/1.1" 404 312
    garbage line
    10.0.0.9 - - [25/Nov/2026:10:18:03 +0000] "GET /index.html HTTP/1.1" 200 5120
    END

my $log_re = qr/
    ^ (?<ip> \S+ ) \s+ \S+ \s+ \S+ \s+ \[ [^\]]+ \] \s+
    " [A-Z]+ \s+ (?<path> \S+ ) [^"]* " \s+ (?<status> \d{3} ) \s+ (?<bytes> \d+ ) $
/x;

my (%status, %ips, $bytes, $bad);

for my $line (split /\n/, $log) {
    unless ($line =~ $log_re) {
        $bad++;
        next;
    }
    $status{ $+{status} }++;
    $ips{ $+{ip} }++;
    $bytes += $+{bytes};
}

say "status $_: $status{$_}" for sort keys %status;
say "unique clients: ", scalar keys %ips;
say "bytes sent: $bytes";
say "unparsed lines: $bad";

The pattern now captures only the fields the summary needs. A line that does not match is counted as unparsed instead of being silently ignored, which helps to notice a wrong pattern or a damaged log. The %ips hash uses addresses as keys, so the number of its keys is the number of distinct clients.

$ perl log_summary.pl
status 200: 2
status 302: 1
status 404: 1
unique clients: 3
bytes sent: 10552
unparsed lines: 1

Parsing an INI file

INI files add sections to key and value lines. A section starts with its name in square brackets and lasts until the next section. The parser has to remember the current section.

ini.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $ini = <<~'END';
    ; global settings
    name = demo

    [database]
    host = localhost
    port = 5432   ; default port

    [paths]
    root = /var/www
    END

my %conf;
my $section = 'main';

for my $line (split /\n/, $ini) {
    $line =~ s/\s*[;#].*//;
    next if $line =~ /^\s*$/;

    if ($line =~ /^\s*\[\s*(\w+)\s*\]\s*$/) {
        $section = $1;
    } elsif ($line =~ /^\s*(\w+)\s*=\s*(.*?)\s*$/) {
        $conf{"$section.$1"} = $2;
    } else {
        warn "cannot parse: $line\n";
    }
}

say "$_ = $conf{$_}" for sort keys %conf;

Every non-empty line is either a section header or a setting. The $section variable holds the name of the current section and starts as main for settings before the first header. Each setting is stored under a combined key such as database.port. A line that matches neither pattern produces a warning, so errors in the file do not go unnoticed.

$ perl ini.pl
database.host = localhost
database.port = 5432
main.name = demo
paths.root = /var/www

Parsing a URL

A URL consists of a scheme, a host, an optional port, a path, a query string and a fragment. Most parts are optional, so the pattern wraps each of them in a group followed by ?.

url.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $url = 'https://example.com:8080/docs/page.html?q=perl&lang=en#top';

my $url_re = qr{
    ^ (?<scheme> [a-z][a-z0-9+.-]* ) ://
    (?<host> [^/:?\#]+ )
    (?: : (?<port> \d+ ) )?
    (?<path> / [^?\#]* )?
    (?: \? (?<query> [^\#]* ) )?
    (?: \# (?<fragment> .* ) )? $
}xi;

$url =~ $url_re or die "not a URL: $url\n";
my %part = %+;

for my $name (qw(scheme host port path query fragment)) {
    say "$name: ", $part{$name} // '(none)';
}

while ($part{query} =~ /([^&=]+)=([^&]*)/g) {
    say "  param $1 = $2";
}

The pattern uses braces as delimiters, so the slashes need no escaping. The # character is escaped, because under /x it starts a comment. The named captures are copied to %part, because the next successful match replaces %+. Missing parts are reported with the defined-or operator //. Finally, a global match in scalar context walks through the query string pair by pair.

The pattern does not decode escapes such as %20. In real programs, the URI module handles these details.

$ perl url.pl
scheme: https
host: example.com
port: 8080
path: /docs/page.html
query: q=perl&lang=en
fragment: top
  param q = perl
  param lang = en

Parsing a CSV line

Splitting a CSV line at commas fails when a quoted field contains a comma. A pattern that knows about quoted fields can walk through the line field by field.

csv.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my $line = 'id,"Novak, Lucia",42,"say ""hi""",,end';

my @fields;

while ($line =~ / \G (?: " ( (?: [^"] | "" )* ) " | ( [^,]* ) ) (,|$) /gx) {
    my ($quoted, $plain, $sep) = ($1, $2, $3);

    push @fields, defined $quoted ? $quoted =~ s/""/"/gr : $plain;
    last if $sep eq '';
}

say scalar(@fields), " fields";
say "[$_]" for @fields;

Each match reads one field, either quoted or plain, and the separator after it. Inside quotes, a field may contain any character except a quote, or a doubled quote, which stands for one quote character. The \G anchor makes each match start exactly where the previous one ended, so no character is skipped. The captures are saved right away, because the substitution in the next line resets them. When the separator is empty, the end of the line has been reached. Real CSV data, which can contain newlines inside fields, is better handled by Text::CSV.

$ perl csv.pl
6 fields
[id]
[Novak, Lucia]
[42]
[say "hi"]
[]
[end]

Validating input

A pattern anchored at both ends checks that a whole value has the expected form. Keeping the patterns in a hash puts all the rules in one place.

validate.pl
#!/usr/bin/perl

use warnings;
use v5.34.0;

my %rule = (
    email => qr/^[\w.+-]+@[\w-]+(?:\.[\w-]+)+$/a,
    date  => qr/^\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])$/a,
    color => qr/^#(?:[0-9a-f]{3}){1,2}$/i,
);

my @tests = (
    email => 'lucia@example.com',  email => 'not an email',
    date  => '2026-11-25',         date  => '2026-13-01',
    date  => '2026-02-31',
    color => '#1A2b3C',            color => '#12345',
);

for (my $i = 0; $i < @tests; $i += 2) {
    my ($type, $value) = @tests[$i, $i + 1];
    my $verdict = $value =~ $rule{$type} ? 'ok' : 'rejected';
    printf "%-6s %-18s %s\n", $type, $value, $verdict;
}

The /a modifier limits \d and \w to ASCII. The date pattern checks the ranges of months and days but not the length of each month, so 2026-02-31 passes. This is typical: a regular expression can reject values of the wrong shape, but it cannot prove that a date exists or that an e-mail address can receive mail. Such checks need a date library or a confirmation message.

$ perl validate.pl
email  lucia@example.com  ok
email  not an email       rejected
date   2026-11-25         ok
date   2026-13-01         rejected
date   2026-02-31         ok
color  #1A2b3C            ok
color  #12345             rejected

Best practices

The following guidelines help when parsing text with regular expressions.

Source

perlre ยท perlretut

In this article we have parsed key and value lines, settings and INI files, web server logs, URLs and CSV lines, and validated input with regular expressions. See also Perl named captures, Perl regex modifiers and Perl global matching.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Perl tutorials.