最新消息:20210917 已从crifan.com换到crifan.org

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

Perl // crifan 2975浏览 0评论

【问题】

需要把对应的html代码:

<h1>h1 content</h1>
<div>
    div test
</div>

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

 

【解决过程】

1.参考了:

Perl正则表达式

Perl Regular Expressions

最后写出如下代码:

#!/usr/bin/perl -w

=File decalaration
Function:
求perl过滤html标签的函数,或正则表达式
http://zhidao.baidu.com/question/510205886.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.替换

$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,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
93 queries in 0.197 seconds, using 23.39MB memory