最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Perl中的正则表达式的替换和后向引用

Perl // crifan 3801浏览 0评论

【问题】

需要把对应的html代码:

1
2
3
4
<h1>h1 content</h1>
<div>
    div test
</div>

中的标签用perl的正则去替换掉。

 

【解决过程】

1.参考了:

Perl正则表达式

Perl Regular Expressions

最后写出如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#!/usr/bin/perl -w
 
=File decalaration
Function:
求perl过滤html标签的函数,或正则表达式
 
Author:     Crifan Li
Version:    2012-12-24
Contact:    admin at crifan dot com
=cut
 
use warnings;
 
$origHtml = <<END;
<h1>h1 content</h1>
<div>
    div test
</div>
 
<invalidTag> invalid tag test </invalid>
END
 
print("origHtml=", $origHtml);
 
$filteredHtml = $origHtml;
$filteredHtml =~  s/<(\w+?)>(.+?)<\/\1>/$2/sg;
#$filteredHtml =~  s/<\w+?>(.+?)<\/\w+?>/$1/sg; # will also remove invalid tag
print "after remove tag=",$filteredHtml;
 
# h1 content
 
    # div test
 
 
# <invalidTag> invalid tag test </invalid>

 

【总结】

Perl中的正则:

1.替换

1
2
$variable "xxx";
$variable =~ s/yyy/zzz/flags;

 

注意:字符串变量必须先初始化,否则u会报错:

Use of uninitialized value $_ in substitution (s///) at xxx.pl line 25.

 

flags:就是正常的参数,详见:Perl正则表达式

 

2.后向引用

使用$N,其中N=1,2,3,…,对应着组的编号

 

3. 总之,Perl中的正则,还是不好用啊。目前觉得,比较好用的正则,是C#,Python等,功能丰富,方便使用。

转载请注明:在路上 » 【已解决】Perl中的正则表达式的替换和后向引用

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
83 queries in 0.262 seconds, using 22.18MB memory