XML technologies / Regular expressions / Perl / The match operator / Different uses of the match operator

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

The match operator can serve as a simple match-or-no-match test, but it can also extract further information and be combined with other match operators. Its behavior depends primarily on context (see Expression context) and on whether the /g modifier is used.

 

Does it match? Scalar context without /g

In scalar context, for example the condition of an if statement, the match operator simply returns true or false:

if ($suchtext =~ m/.../) {
    # Code für den Treffer-Fall,
    .
    . 
    .
} else {
    # Code für den Fall, dass kein Treffer erzielt wird.
    . 
    . 
    .
}

The Boolean result can also be assigned to a variable and tested later:

my $gefunden = $suchtext =~ m/.../;
  .
  . 
  .
if ($gefunden) {
  .
  . 
  .
}

 

Extracting data from the subject string: list context without /g

The match operator is normally used in list context without the /g modifier to extract data. It returns a list of the local matches captured by parenthesized subexpressions in the regex. For example, extract year, month, and day from a string such as 69/8/31 as follows:

my ($jahr, $monat, $tag) = $datum =~ m{^ (\d+) / (\d+) / (\d+) $}x;

The three numbers are now available in three variables, as well as in $1, $2 and $3. The returned list contains one element per capturing pair, or is empty on failure.

A parenthesized group may contribute nothing to the match, as necessarily happens in m/(klipp)|(klar)/. It still receives a list element, with an undefined value. If the regex has no parentheses, success returns the list (1), and failure an empty list.

List context can be created in several ways, for example by assigning to an array variable:

my @teile  =  $text =~ m/^(\d+)-(\d+)-(\d+)$/;

If only the first capture matters, a scalar would suffice. Nevertheless, list context must be forced; otherwise, only the success/failure Boolean is stored. Compare:

my ($wort)    =  $text =~ m/(\w+)/;
my $gefunden  =  $text =~ m/(\w+)/;

In the first case, parentheses around the variable tell the my declaration to create list context for the assignment and therefore the search. The second case supplies scalar context, so $gefunden receives only the Boolean result.

The next example shows a common idiom:

if ( my ($jahr, $monat, $tag) = $datum =~ m{^ (\d+) / (\d+) / (\d+) $}x ) {
    # Code für den Treffer-Fall: $jahr usw. sind verfügbar.
} else {
    # Code für den Fall, dass kein Treffer erzielt wird.
}

The match operator has list context, forced by the parentheses in ›my (...) =‹. A successful search therefore returns the list of variables $1, $2 and so on. But the entire expression is the condition of an if statement, so Perl must convert the list to a scalar. A list’s scalar value is its element count: positive, hence true, on success, and conveniently zero on failure.

 

Extracting all matches: list context with /g

This useful construct returns not just the captured texts from one match, but all such texts found across every iteration of /g . Without capturing parentheses, it returns all complete matches.

This simple example extracts all natural numbers in a string:

my @nums  =  $text =~ m/\d+/g;

If $text contains an IP address such as ›64.156.215.240‹, then @nums receives four elements: ›64‹, ›156‹, ›215‹ and ›240‹. Combined with other language features, this can print an IP address as an eight-digit hexadecimal number such as ›409cd7f0‹, saving space in a log file, for example:

my $hex_ip = join '', map { sprintf("%02x", $_) } $ip =~ m/\d+/g;

A similar approach reconstructs the IP address:

my $ip = join '.', map { hex($_) } $hex_ip =~ m/../g

To extract numbers with decimal parts, use:

my @nums  =  $text =~ m/\d+(?:\.\d+)?|\.\d+/g;

Noncapturing parentheses are essential here; capturing ones return different data. Sometimes that is exactly what we want, as here:

my @Tags  =  $Html =~ m/<(\w+)/g;

The array @Tags receives all HTML tags in their order within $Html , assuming that ›<‹ characters occur only as part of HTML tags.

Multiple capturing groups work too. Here, an entire alias file, such as those used by Unix mail programs, is stored in one string. Its logical lines look like this:

alias  Jeff      jfriedl@regex.info
alias  Perlbug   perl5-porters@perl.org
alias  king      elvis@tabloid.org

A regex such as m/^alias\s+(\S+)\s+(.+)/m without /g matches an alias and its address. In list context, the operator returns two elements, for example ('Jeff', 'jfriedl@regex.info'). With /g, we obtain every pair, a list like:

( 'Jeff', 'jfriedl@regex.info', 'Perlbug', 'perl5-porters@perl.org', 'king', 'elvis@tabloid.org' )

This list contains key-value pairs that can be assigned directly to an associative array. After

my %alias  =  $text =~ m/^alias\s+(\S+)\s+(.+)/mg;

, $alias{Jeff} contains the complete address of ›Jeff‹.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top