Master Regular Expressions 2nd Edition(二)

来源:互联网 发布:刺客知伯 编辑:程序博客网 时间:2024/05/19 04:53

修改文本
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

原创粉丝点击