XML technologies / Regular expressions / Extended introductory examples / Modifying text with regular expressions / Code example: stock prices

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

Another problem arose in a stock-price program. I received values such as “9.0500000037272”, clearly intended as 9.05. Limited internal floating-point precision can make Perl print that representation. Normally I would use printf to print two decimal places, as in the temperature-conversion example (see Extended introductory examples: the examples and following sections), but not here. US stock prices then used mixed fractions such as “12 1/8”, for which we need “12.125”, not just two decimal places.

I chose⟦U+0002⟧ this method: always show the first two decimal places, show the third only if nonzero, and discard the rest. This turns 12.3750000000392 or even the already-correct 12.375 into “12.375”, while 37.500 becomes “37.50”, just as desired.

How do we implement this? Variable $kurs contains the input string, so try:

$kurs =~ s/(\.\d\d[1­9]?)\d*/$1/

Recall that ˹\d˼, introduced in Pattern matching with regexes: recap, matches a digit.

The leading ˹\.˼ matches the decimal point, and the following ˹\d\d˼ matches its first two digits. The ˹[1­-9]?˼ matches only if the third digit is nonzero. Everything matched so far must be retained, so parentheses capture it in variable $1. We use this $1 in the replacement text. If that were the whole regex, it would merely replace the matched string with itself. But the regex continues beyond the parentheses. Characters matched by this part of the regex are not stored in $1 and thus do not enter the replacement: they are deleted. Here, these are the extra digits matched by the final ˹\d*˼.

In How regex engines work, we will revisit this example to examine what happens during matching. Its variations offer several interesting lessons.

  

 

 

 

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