【发布时间】:2014-07-15 15:09:51
【问题描述】:
我正在尝试构建一个 Perl 正则表达式来匹配这样的字符串:
no tags
beginning<tag>this is tag</tag>rest of line
<tag1>this is tag1</tag1>
<tag1>this is tag1</tag1>rest of line
我想使用分组来提取标签以及它们之间的内容。
我试过用这个:
$a="beginning<tag>this is tag</tag>rest of line";
print "a=$a\n\n";
($x0, $x1, $x2, $x3, $x4, $x5) = ($a =~ /(.*?)(<tag>)(.*)(<\/tag>)(.*)/);
print "x0=$x0\n";
print "x1=$x1\n";
print "x2=$x2\n";
print "x3=$x3\n";
print "x4=$x4\n";
a=beginning<tag>this is tag</tag>rest of line
x0=beginning
x1=<tag>
x2=this is tag
x3=</tag>
x4=rest of line
我想要什么,但如果这是源字符串:
a=there are no tags
x0=
x1=
x2=
x3=
x4=
没有匹配项。
【问题讨论】:
-
不要使用正则表达式解析 HTML。使用适当的 HTML 解析模块。 您无法使用正则表达式可靠地解析 HTML,并且您将面临悲伤和挫败感。一旦 HTML 与您的期望发生变化,您的代码就会被破坏。请参阅htmlparsing.com/php 或this SO thread,了解如何使用已经编写、测试和调试过的 PHP 模块正确解析 HTML。
-
-
您可以随时将模块的代码直接复制/粘贴到您的程序中。
标签: regex perl html-parsing