PERL REGEX coincidente InfoHash de Imán Link
-
15-11-2019 - |
Pregunta
Estoy tratando de extraer un hash de información de un enlace de imán torrent usando Perls regex
El enlace magnet parece:
imán :? xt= urn: btih: 8AC3731AD4B039C05393B5404AFA6E7397810B41 & DN= Ubuntu + 11 + 10 + Oneiric + Ocelot + Desktop + CD + i386 & tr= http% 3a% 2f% 2ftracker.openbittorrent.com% 2fannuteunco
pero a veces puede parecerse:
imán :? xt= urn: btih: 8AC3731AD4B039C05393B5404AFA6E7397810B41
La parte que intento extraer es 8AC3731AD4B039C05393B5404AFA6E7397810B41
Estoy tratando de capturar todo hasta la primera '&' o si solo incluye el InfoHash, hasta el final de la línea, he intentado un par de pareja, pero no puedo hacer que funcione correctamente y lo que tengo por debajo de las capturas solo.el primer carácter
if ($tmpVar =~ m/magnet\:\?xt=urn\:btih\:([[:alnum:]]+?)/i) {
$mainRes{'hash'} = $1;
}
También intenté agregar y $ después de la captura, pero eso simplemente resulta en un error Gracias
Solución
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
Otros consejos
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.