Tuesday, October 4, 2011

Perl -- Regular Expressions

A是检查是不是在首位,$是检查是不是在末位, "."点是替代一个字符,"+"代表one or more; "?"问号是代表0个,1个或多个
\w Match a "word" character (alphanumberic plus "_")
\W Match a non-word character
\s Match a whitespace character
\S Match a non-whitespace character
\d Match a digit character
\D Match a non-digit character

1)m match operator
$string = "hErE Is a STriNg";
if($string =~ m/here is a string/i)
{
 print "It's a match!\n";
}

m//  ##match 匹配
i    ##忽略大小写
可以写成 /.../; m!...!; m#...#;

2)s subsitution
$string =~ s/here/There/i;
结果是There Is a STriNg

s/ / /i ##substution用后一个字符串取代前一个字符串

3)
$string = "I see the road.";
$string =~ tr/r/t/;

结果是"I see the toad";
tr/r/t/; 用后一个字符取代前一个字符。

4)
$string = "Perl is coooooooooool!";
$string =~ s/o+/oo/g;
结果是"Perl is cool!";
s/o+/oo/g

5) number
$number = 123;
if($number =~ /^\d+$/){
print "it is a number!\n";
}
/^\d+$/检查是不是number

6)
$letters = "abc";
if($letters =~ /^[A-Za-z]+$/)
{print "Letter only!";}

7)去掉空格
$stirng1 = "     Leading whitespace.";
$string2 = "Trailing whitespace.    ";

$string1 =~ s/^\s+//;
$string2 =~ s/\s+$//;

No comments: