1

嗨,我需要获取 $submitkey 的值 mjxjezhmgrutgevclt0qtyayiholcdctuxbwb。我的代码有什么问题?

my $str = '<input type="hidden" value="set" name="fr.posted"></input><input type="hidden" value="mjxjezhmgrutgevclt0qtyayiholcdctuxbwb" name="fr.submitKey"></input><div class="form-actions form-actions__centrate"><button value="clicked" id="hook_FormButton_button_accept_request" onclick="className +=" button-loading"" class="button-pro form-actions__yes" type="submit" name="button_accept_request"><span class="button-pro_tx">Войти</span>';
($submitkey) = $str =~ m/value="(.*?)" name="fr.submitKey"/;
print $submitkey;
4

4 回答 4

2

永远不要使用.*?. 这从来都不是你真正想要做的。即使你让它工作,当没有匹配时,它也很可能产生极差的性能。在这种情况下,使用[^"]*

于 2012-11-14T20:26:59.663 回答
1

.*?不会导致 Perl 在整个字符串中搜索最短的匹配项。因此,匹配字符串前面的文本.*?,Perl 很高兴它在那里找到了匹配项。.*?仅仅意味着它从匹配之前部分的第一个点开始匹配尽可能少的字符.*?

正如@ikegami 所说:[^"]*在您的特定情况下使用。

于 2012-11-14T20:30:14.993 回答
1

您从第一个实例一直匹配value"fr.submitKey".

利用每个值都包含在引号中的事实;仅查找非引号字符作为value.

此外,使用特殊的捕获组变量更简洁:

my $str = '<input type="hidden" value="set" name="fr.posted"></input><input type="hidden" value="mjxjezhmgrutgevclt0qtyayiholcdctuxbwb" name="fr.submitKey"></input><div class="form-actions form-actions__centrate"><button value="clicked" id="hook_FormButton_button_accept_request" onclick="className +=" button-loading"" class="button-pro form-actions__yes" type="submit" name="button_accept_request"><span class="button-pro_tx">Войти</span>';
$str =~ m/value="([^"]*)" name="fr.submitKey"/;
$submitkey = $1;
print $submitkey;
于 2012-11-14T20:30:29.960 回答
0

为这个任务使用真正的 DOM 解析器要好得多。我喜欢Mojo::DOM,它是Mojolicious工具套件的一部分。请注意,use Mojo::Base -strict启用和。该方法使用 CSS3 选择器找到第一个匹配的实例。strictwarningsutf8at

#!/usr/bin/env perl

use Mojo::Base -strict;
use Mojo::DOM;

my $dom = Mojo::DOM->new(<<'END');
<input type="hidden" value="set" name="fr.posted"></input><input type="hidden" value="mjxjezhmgrutgevclt0qtyayiholcdctuxbwb" name="fr.submitKey"></input><div class="form-actions form-actions__centrate"><button value="clicked" id="hook_FormButton_button_accept_request" onclick="className +=" button-loading"" class="button-pro form-actions__yes" type="submit" name="button_accept_request"><span class="button-pro_tx">Войти</span>
END

my $submit_key = $dom->at('[name="fr.submitKey"]')->{value};
say $submit_key;
于 2013-06-23T23:27:18.063 回答