Search code examples
regexperlmagnet-uri

perl regex matching infohash from magnet link


im trying to extract an info hash from a torrent magnet link using perls regex
the magnet link looks like:

magnet:?xt=urn:btih:8AC3731AD4B039C05393B5404AFA6E7397810B41&dn=ubuntu+11+10+oneiric+ocelot+desktop+cd+i386&tr=http%3A%2F%2Ftracker.openbittorrent.com%2Fannounce

but sometimes it can look like:
magnet:?xt=urn:btih:8AC3731AD4B039C05393B5404AFA6E7397810B41

the part im trying to extract is 8AC3731AD4B039C05393B5404AFA6E7397810B41

im trying to capture everything upto the first '&' or if it only includes the infohash then upto the end of the line, ive tried a couple way but cant get it to work correctly
what i have below only captures the first character

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

i also tried adding &|$ after the capture but that just results in an error
Thanks


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