Domanda

Sto cercando di estrarre un hash informazioni da un collegamento di magnete torrent usando Perls Regex
Il collegamento Magnet sembra:

Magnete :? XT= URN: BTIH: 8AC3731AD4B039C05393b5404AFA6E7397810AF41E7397810B41 & DN= Ubuntu + 11 + 10 + oneirico + ocelot + desktop + cd + i386 & tr= http% 3a% 2f% 2fracker.openbittorrent.com% 2

Ma a volte può sembrare:
Magnete :? XT= URN: BTIH: 8AC3731AD4B039C05393B5404AFA6E7397810B41

La parte sto cercando di estrarre è 8ac3731AD4B039C05393B5404AFA6E7397810B41

Sto cercando di catturare tutto fino al primo '&' o se include solo l'infohash poi fino alla fine della linea, ho provato un paio di modi, ma non riesco a farcela funzionare correttamente a quello che ho sotto solo catturail primo carattere

if ($tmpVar =~ m/magnet\:\?xt=urn\:btih\:([[:alnum:]]+?)/i) {
  $mainRes{'hash'} = $1;
}
.

Ho anche provato ad aggiungere e | $ dopo la cattura, ma che si traduce solo in un errore Grazie

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top