正则习点 --- 04

阅读更多

Chapter 2. Extended IntroductoryExamples

2.1 Matching Text with RegularExpressions

请看代码:

#! /usr/bin/perl -w # Mastering Regular Expressiona: Chapter 2Section 2. # first program print "Enter a temperature inCelsius:\n"; $celsius = ; chomp($celsius); if ( $celsius =~ /^[0-9]+$/) { $fahrenheit= ($celsius * 9 / 5) + 32; print"$celsius C is $fahrenheit F\n"; } else { print"Expecting a number, so I don't understand\"$celsius\".\n"; }


两端「^…$」的保证整个$reply只包含数字。

2.1.1 Toward a More Real-WorldExample

改进上一个程序,使之能容许负数和小数部分。

我们需要三个子表达式:负数符(-)、数字、小数

a.负数符 [-+]?

首先,有一个或者多个负数符号;然后,可以有负数符号,也可以没有。

b.数字 [0-9]+

首先,容许数字;然后,可以是一位或者多位。

c.小数

可以有小数部分,也可以没有。

(1)小数点 /.*

首先,转义小数点;然后,可以没有小数点,也可以有多个。

(2)小数部分的数字 [0-9]*

首先,容许数字;然后,可以有数字,也可以有多个。

组合起来就是:/^[-+]?[0-9]+(/.*[0-9]*)?$/

这样一个摄氏转华氏的程序,就完成了。

完整代码:

#! /usr/bin/perl -w # Mastering Regular Expressiona: Chapter 2Section 2. # first program print "Enter a temperature in Celsius:\n"; $celsius = ; chomp($celsius); if ( $celsius =~/^[-+]?[0-9]+(\.[0-9]*)?$/) { $fahrenheit= ($celsius * 9 / 5) + 32; print"$celsius C is $fahrenheit F\n"; } else { print"Expecting a number, so I don't understand\"$celsius\".\n"; }


你可能感兴趣的:(正则习点 --- 04)