打印本文 打印本文 关闭窗口 关闭窗口
Master Regular Expressions 2nd Edition(二)
作者:武汉SEO闵涛  文章来源:敏韬网  点击数978  更新时间:2006/7/27  文章录入:mintao  责任编辑:mintao

修改文本
1、Perl中的替换表达式为:
$var =~ s/regex/replacement/
可以在replacement中使用$1等变量

2、Perl中<>表示一行文本

3、definded($val)查看一个变量是否有定义

4、lookaround:定位标识,定位到匹配文本位置之前或之后
lookahead(定位在前):(?=...)
lookback(定位在后):(?<=...)

5、/g选项表示global replacement,全部替换

6、s/(?<=\bJeff)(?=s\b)/''''/g
搜索一个位置,这个位置前面是Jeff,后面是s,然后在这个位置上加''''

7、s/(?=s\b)(?<=\b Jeff)/''''/g 和 s/(?<=\bJeff)(?=s\b)/''''/g 表达了同一个位置

8、给整数每三位加上一个逗号,比如123456789变成123,456,789
$pop =~ s/(?<=\d)(?=(\d\d\d)+$)/,/g;
或者
(?<=\d)(?=(?:\d\d\d+$)
其中多加了(?:...)表示不参与子匹配,更有效率,但相对复杂难懂
$pop =~ s/(?<=\d)(?=(\d\d\d)+(?!\d))/,/g;才是正确的,晕。原因是$,所以使用Negative Lookahead来替换

9、位置匹配的四种情况:
Type Regex Successful if the enclosed subexpression . . .
Positive Lookbehind (?<=......) successful if can match to the left
Negative Lookbehind (?<!......) successful if can not match to the left
Positive Lookahead (?=......) successful if can match to the right
Negative Lookahead (?!......) successful if can not match to the right

打印本文 打印本文 关闭窗口 关闭窗口