第七章 正则模式

前端之家收集整理的这篇文章主要介绍了第七章 正则模式前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
模式分组:

在数学中,圆括号() 用来分组。因此,圆括号也是元字符

模式/fred+/ 会匹配像fredddddd这样的字符窜

/(fred)+/ 会匹配像fredfredfred这种字符窜

[root@jhoa 2015]# cat a8.pl 
$_="abba";
if (/(.)\1/){ ##匹配bb
 print "It matched same character next to itself!\n";
 print "\$1 is $1\n";
}


[root@jhoa 2015]# perl a8.pl 
It matched same character next to itself!
$1 is b

(.)\1 表明需要匹配连续出现的两个同样的字符



反向引用不必总是附在相应的括号后面,下面的模式会匹配y后面的4个连续的非回车字符,并且用\1在d字符之后重复这个4个字符




[root@jhoa 2015]# cat a9.pl 
$_ = "yabba dabba doo";
if (/y(....) d\1/) {
  print "It matched the same after y and d !\n";
  print "\$1 is $1\n";
}
[root@jhoa 2015]# perl a9.pl 
It matched the same after y and d !
$1 is abba


[root@jhoa 2015]# cat a11.pl 
$_ = "yabba dabba doo";
if (/y(.)(.)\2\1/)  {
  print "It matched the same after y and d !\n";
  print "\$1 is $1\n";
  print "\$2 is $2\n";
}
[root@jhoa 2015]# perl a11.pl 
It matched the same after y and d !
$1 is a
$2 is b


匹配的是abba



$_ = "yabba dabba doo";
if (/y((.)(.)\3\2) d\1/) {
  print "It matched the same after y and d !\n";
  print "\$1 is $1\n";
  print "\$2 is $2\n";
}
~                                                                                                    
~  (
/y(
(.)(.)\3\2

) d\1/

)                                                                                                   
~    


[root@jhoa 2015]# cat a10.pl 
$_ = "yabba dabba doo";
if (/y((.)(.)\3\2) d\1/) {
  print "It matched the same after y and d !\n";
  print "\$1 is $1\n";
  print "\$2 is $2\n";
  print "\$3 is $3\n";
}
[root@jhoa 2015]# perl a10.pl 
It matched the same after y and d !
$1 is abba
$2 is a
$3 is b

匹配abbd dabbd d












原文链接:https://www.f2er.com/regex/360717.html

猜你在找的正则表达式相关文章