XML technologies / Regular expressions / Extended introductory examples / Pattern matching with regular expressions / Side effects of a successful match

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

Let us extend the program so the user can enter Fahrenheit or Celsius by specifying C or F after the temperature. To make our regular expression understand this, we simply append ˹[CF]˼. We must now adapt the rest of the program to determine whether Fahrenheit or Celsius was entered and calculate the other temperature.

In Introduction to regular expressions we saw that some versions of egrep support the metacharacters ˹\1˼, ˹\2˼ , ˹\3˼ and so on within a regex. These are also supported in Perl and most modern languages using regular expressions. These languages also provide access to the text matched by parenthesized parts of a regex.

We will see how other languages handle this in Features and dialects. In Perl, these variables are called $1, $2, $3 and so on. They refer to the text matched by the first, second and third parenthesized subexpressions, respectively. Strange as they look, they are variables; their names are simply numbers. In Perl, these variables are set whenever a regular expression matches successfully.

To recap: the metacharacter ˹\1˼ is used inside a regular expression to access text matched earlier by that same expression; the variable $1 serves the same purpose outside the regex, after matching.

To focus on the new features and keep the example clear, I temporarily omit the part handling decimal places. To illustrate the use of $1, compare

$celsius =~ m/^[­+]?[0­9]+[CF]$/

and

$celsius =~ m/^([­+]?[0­9]+)([CF])$/

Do the additional parentheses change the regular expression’s meaning? To answer, we must check whether they form groups for the star or other quantifiers, or delimit alternatives (˹|˼). Both answers are no, so the two expressions match the same thing. The second has parentheses because they mark “interesting” parts of the subject string. As the following figure shows, $1 will contain the entered number and $2 the entered letter, C or F. The flowchart in the figure after next shows how to proceed after matching.

  Capturing text with parentheses

Figure: capturing text with parentheses.

Temperature-conversion flowchart

Figure: temperature-conversion flowchart.

Temperature-conversion program.

print "Geben Sie eine Temperatur ein (z.B. 32F, 100C):\n";
$eingabe = <STDIN>; # liest eine Eingabe-Zeile
chomp($eingabe);    # entfernt das Newline von $eingabe
if ($eingabe =~ m/^([­+]?[0­9]+)([CF])$/)
{      
      # Mustererkennung war erfolgreich. $1 ist die Zahl, $2 ist "C" oder "F".
      $EingabeZahl = $1; # in benannte Variablen kopieren, ...
      $Typ = $2;         # ... damit der Rest des Programms lesbarer wird.
      if ($Typ eq "C") { # ›eq‹ vergleicht zwei Strings
            # Eingabe war in Celsius, also Fahrenheit berechnen
            $celsius = $EingabeZahl;
            $fahrenheit = ($celsius * 9 / 5) + 32;
      } else {
            # Kein "C", muss daher ein "F" sein, also Celsius berechnen
            $fahrenheit = $EingabeZahl;
            $celsius = ($fahrenheit ­ 32) * 5 / 9;
      }
      # Hier haben wir beide Temperaturen, Resultat ausgeben:
      printf "%.2f C = %.2f F\n", $celsius, $fahrenheit;
} else {
      # Regex passt nicht: Warnung ausgeben.
      print "Zahl, gefolgt von \"C\" oder \"F\", erwartet,\n";
      print "nicht \"$eingabe\".\n";
}

If the file containing the program on the preceding page is called konvert, it is used as follows:

 % perl ­-w konvert
 Geben Sie eine Temperatur ein (z.B. 32F, 100C):
 39F
 3.89 C = 39.00 F
 % perl -­w konvert
 Geben Sie eine Temperatur ein (z.B. 32F, 100C):
 39C
 39.00 C = 102.20 F
 % perl -­w konvert
 Geben Sie eine Temperatur ein (z.B. 32F, 100C):
 oops
 Zahl, gefolgt von "C" oder "F", erwartet,
 nicht "oops".

  

 

 

 

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