【发布时间】:2014-08-07 16:49:38
【问题描述】:
我是 perl 和正则表达式的新手。我想我理解这个想法以及如何使用正则表达式,但我在编写脚本时遇到了一个问题。我有一些页面的内容,我正在尝试阅读一些信息。
my @rows = split(/<tr(\s)bgcolor=.{8}/,$content);
foreach my $row(@rows){
if( $row =~/<td\s+nowrap\s+align=.*\s?(bgcolor=.*\s+)?>\w*\s?<\/td>/ig){
print $1;
print $file_opt $row."\n";
# there will be more code later on
}
}
这给了我一个$1 未初始化的错误。我知道当模式与字符串不匹配时会发生这种情况。但是我在 if 下有正则表达式 - 所以如果它进入 if,它确实匹配,对吗?如您所见,我将行打印到文件中。每个看起来像这样:
<td nowrap align="right">DOLNOŚLĄSKIE</td><td nowrap align="right" bgcolor=#D0E0D0 >0</td><td nowrap align="right">0</td><td nowrap align="right" bgcolor=#D0E0D0 >0</td><td nowrap align="right">0</td><td nowrap align="right" bgcolor=#D0E0D0 >0</td><td nowrap align="right">0</td><td nowrap align="right" bgcolor=#D0E0D0 >0</td><td nowrap align="right">0</td><td nowrap align="right" bgcolor=#D0E0D0 >0</td><td nowrap align="right">4</td><td nowrap align="right" bgcolor=#D0E0D0 >0</td><td nowrap align="right">1</td><td nowrap align="right" bgcolor=#D0E0D0 >1</td><td nowrap align="right">3</td><td nowrap align="right" bgcolor=#D0E0D0 >6</td><td nowrap align="right">1</td><td nowrap align="right" bgcolor=#D0E0D0 >2</td><td nowrap align="right">1</td><td nowrap align="right" bgcolor=#D0E0D0 >19</td><td nowrap align="right">0</td></tr>
来自$content 的所有不必要的东西都不在文件中。那么这个模式是否匹配?
【问题讨论】:
-
改用解析器。
-
不要为此使用正则表达式。请改用 HTML 解析器。
-
不要使用正则表达式解析 HTML。使用适当的 HTML 解析模块。 您无法使用正则表达式可靠地解析 HTML,并且您将面临悲伤和挫败感。一旦 HTML 与您的期望发生变化,您的代码就会被破坏。有关如何使用已经编写、测试和调试的现有 Perl 模块的示例,请参阅 htmlparsing.com/perl。
-
感谢您的建议。我想我有示例代码的大学并不像每个男孩想象的那么好:D
标签: regex perl html-parsing