マグネットリンクからのInfoHashを一致させるPerl regexマッチング

StackOverflow https://stackoverflow.com/questions/9520726

  •  15-11-2019
  •  | 
  •  

質問

Perls regexを使用して急流のマグネットリンクから情報ハッシュを抽出しようとしています
マグネットリンクは次のようになります。

磁石:?XT= URN:BTIH:8AC3731AD4B039C05393B5404AFA6E7397810B41&DN= UBUNTU + 11 + 10 + ONEILIC + OCELOT + 10 + DESKTOP + CD + I386&TR= HTTP%3A%2F%2FTRACKER.OPENBITRENT.COM%2ファンクション

しかし時々それは次のように見えることがあります:
マグネット:?XT= URN:BTIH:8AC3731AD4B039C05393B5404AFA6E7397810B41

抽出しようとしている部分IMは8AC3731AD4B039C05393B5404AFA6E7397810B41 です。

imは最初の '&'までのすべてを捕らえようとしているか、それがそれが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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top