perl regex correspondant infoHash à partir d'aimant lien
-
15-11-2019 - |
Question
im essayer d'extraire une info hachage d'un lien d'aimant torrent à l'aide de Perls Regex
Le lien d'aimant ressemble à:
Aimant :? xt= urn: BTIH: 8AC3731AD4B039C05393B5404AFA6E7397810B41 & DN= Ubuntu + 11 + 10 + Oneiric + Ocelot + Desktop + CD + I386 & TR= HTTP% 3A% 2f% 2ftracker.openbittorrent.com% 2Fannounce
Mais parfois, on peut ressembler à:
Aimant :? xt= urn: BTIH: 8AC3731AD4B039C05393B5404AFA6E7397810B41
La partie im essayant d'extraire est le 8AC3731AD4B039C05393B5404AFA6E7397810B41
Je suis en train d'essayer de tout capturer jusqu'à la première "&" ou si cela n'inclut que l'infoHash puis à la fin de la ligne, j'ai essayé un couple, mais je ne peux pas le faire fonctionner correctement ce que j'ai ci-dessous seulement capturesle premier caractère
if ($tmpVar =~ m/magnet\:\?xt=urn\:btih\:([[:alnum:]]+?)/i) {
$mainRes{'hash'} = $1;
}
J'ai aussi essayé d'ajouter & | $ après la capture mais cela donne simplement une erreur
Merci
La solution
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
Autres conseils
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.