文章目录
前言
本文主要记录perl学习过程中,如何进行正则匹配。
8 以正则表达式进行匹配(2)
这里主要介绍:捕获变量,通用量词,优先级,
8.1 捕获变量
#小括号的两个功能:分组,捕获。
$_ = "Hello there, neighbor";
if(/
\s #空格
(\w+) #一个或者多个字符
, #逗号
/x) #匹配中的空格或回车,不参与匹配
{print "$1 \n";} #捕获的变量存入$1,输出there
# \S表示非空格
if(/(\S+) (\S+), (\S+)/){
print "$1 $2 $3 \n";
}
# ?:表示只分组,不捕获
$value = "one two three four five six";
if($value =~ /(?:\S+) (\S+) (\S+)/){
print "$1 $2 \n"; # two three
}
$value = "you and me";
if($value =~ /(\w+) (?:and|or) (\w+)/){
print "$1, $2 \n"; #you, me
}
# 命名捕获,将捕获到的变量取个名字,捕获到的数据存储在$+的哈希中
$value = "you and me";
if($value =~ /(?<v1>\w+) (?:and|or) (?<v2>\w+)/){
print "$+{v1}, $+{v2} \n"; #you, me
}
# 捕获过程中的反向引用
$names = "Fred Gates and Wilma Gates";
if($names =~ /(?<last_name>\w+) and \w+ \g{last_name}/){
print "$+{last_name}\n"; # Gates
}
# $& 表示正则表达式匹配到的全部
# $'(单引号) 表示匹配到的部分,后面的值
# $`(反引号) 表示匹配到的部分,前面的值
$_ = "one two three, four five six";
if(/\s(\w+),/){
print "$1\n"; #three
print "$&\n"; # three,
print "$'\n"; # four five six
print "$`\n"; #one two
}
8.2 通用量词
{N}表示指定N个
{N, M} 表示最少N个,最多M个,M不写表示无穷个
?表示一个或者零个,等价于{0, 1}
*表示可以没有,也可以有很多个,等价于{0,}
+表示至少有一个,或者很多个,等价于{1,}
8.3 处理优先级
从上到下,优先级依次降低。
8.4 模式测试程序
用于测试我们的正则表达式的小程序。
while(<>){
chomp;
if(/你的正则表达式/){
print "匹配上了:|$`<$&>$'|\n"
}else{
print "没匹配上!\n"
}
}
总结
本文主要记录一些以正则表达式进行匹配的基本用法。