سؤال

أنا أحاول استخراج معلومات التجزئة من رابط مغناطيس سيل باستخدام Perls Regex
الرابط المغناطيس يشبه:

المغناطيس:

ولكن في بعض الأحيان يمكن أن يبدو:
المغناطيس :؟ xt= urn: btih: 8AC3731AD4B039C05393B5404AFA6E7397810B41

الجزء IM الذي يحاول استخراج هو 8AC3731AD4B039C05393B5404AFA6E7397810B41

أنا أحاول التقاط كل شيء حتى الأول '&' أو إذا كان ذلك يتضمن فقط infohash ثم حتى نهاية السطر، جربت إيف بضع طريقة ولكنها غير قادر على الحصول عليها بشكل صحيح - ما لدي أدناه يلتقط فقطالحرف الأول giveacodicetagpre.

حاولت أيضا إضافة & | $ بعد التقاط ولكن فقط يؤدي إلى خطأ شكرا

هل كانت مفيدة؟

المحلول

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