Perl Regex Matching Infohash 자석 링크에서
-
15-11-2019 - |
문제
펄스 정규식을 사용하여 토런트 자석 링크에서 정보 해시를 추출하려고합니다.
자석 링크는 다음과 같습니다.
자석 :? xt= urn : btih : 8AC3731AD4B039C05393B54039C05393B5404AFA6E7393B5404AFA6E7397810B41 & DN= Ubuntu + 11 + 10 + oneiric + ocelot + 데스크탑 + CD + i386 + http % 3A % 2F % 2FTRACKER.OPENBITTORRENT.com % 2
자석 :? xt= urn : btih : 8AC3731AD4B039C05393B5404AFA6E7397810B41
추출하려고하는 부분은 8AC3731AD4B039C05393B5404AFA6E7397810B41 입니다.
첫 번째 '&'까지 모든 것을 캡처하려고하거나 infohash 만 포함 된 경우, 라인의 끝까지, ive는 몇 가지 방법을 시도했지만, 내가 가지고있는 것만 캡처하는 것만으로 올바르게 작동 할 수 없습니다.첫 번째 문자
if ($tmpVar =~ m/magnet\:\?xt=urn\:btih\:([[:alnum:]]+?)/i) {
$mainRes{'hash'} = $1;
}
.
또한 캡처 후 & | $를 시도했지만 오류가 발생합니다. 감사합니다
해결책
You could use:
/\burn:btih:([A-F\d]+)\b/i
Or if the hash is always 40 chars:
/\burn:btih:([A-F\d]{40})\b/i
다른 팁
As you've already discovered, you don't want to use the ?
in your regular-expressions. Here's why:
The ?
in pattern+?
makes your regex "non-greedy", meaning it will try to use as few characters as possible while still matching the pattern you specify. So
"8AC3731AD4B039C05393B5404AFA6E7397810B41" =~ /(\w+?)/
just returns "8
" while
"8AC3731AD4B039C05393B5404AFA6E7397810B41" =~ /(\w+)/
returns the whole string.
if ($tmpVar =~ m/magnet:\?xt=urn:btih:([[:alnum:]]+)/i) {
$mainRes{'hash'} = $1;
}
This is why the gods of CPAN gave us URI, to parse out parts of URIs, which you can then parse with a regex.
#!/usr/bin/perl
use URI;
use URI::QueryParam;
use Data::Dumper;
my $u = URI->new( shift() );
my $xt = $u->query_form_hash->{xt};
my ($hash) = $xt =~ m{^urn:btih:(.*)$};
print "$hash\n";
Presuming your magnet URI on the command line.