Master Regular Expressions 2nd Edition(二)

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

修改文本

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

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航