XML technologies / Regular expressions / Extended introductory examples / Pattern matching with regular expressions / A more practical example
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
Allowing negative and fractional temperatures would be useful. The calculation itself poses no problem: Perl generally does not distinguish natural, integer and floating-point numbers. The regex must change, however. We can insert ˹-?˼ at the start to allow a minus sign. We can also use ˹[-+]?˼, since a plus sign does no harm.
For the fractional part, we specify ˹(\.[0-9]*)?˼. The escaped dot matches a literal decimal point. Thus ˹\.[0-9]*˼ matches a dot followed by any number of digits. Because ˹\.[0-9]*˼ is enclosed in ˹(...)?˼, it is optional. This differs from ˹\.?[0-9]*˼, which would match even without a dot.
Putting everything together gives:
if ($celsius =~ m/^[+]?[09]+(\.[09]*)?$/) {This accepts inputs such as 32, -3.723 and +98.6. It is not perfect: numbers without digits before the decimal point, such as .357, are not allowed, whereas 0.357 is, so we will leave it there. Matching floating-point numbers has some tricky subtleties, explained in greater detail in Practical regex techniques.
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