I tried the above regular expression and it didn't work, so I created my own. I looked at the Wikipedia Magnet URI scheme which states that the magnet identifier is Base32, which means:
Base32 is a base-32 transfer encoding using the twenty-six letters A-Z and six digits 2-7. [Although my understanding is that these digits and letters can be interpolated at random].
As a result, we're looking for the following in a regex:
- The word magnet followed by a semicolon, a questionmark and an "xt=urn:" string
- Any number of strings / numbers up to the next semi-colon (the question's regex fails this)
- From our research above, 32 characters (base32) of interpolated letters and numbers
The beginning /
and the ending /
have to be there, because it's a regex, to denote the start and end, and the i
at the end (/i
) denotes a case-insensitive regex. If we didn't do the /i
, we'd be having to check for [a-zA-Z0-9]
.
The final regex, which actually works, is as follows:
/magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{32}/i
You can try this for yourself:
var torrent = "magnet:?xt=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C";
if (torrent.match(/magnet:\?xt=urn:[a-z0-9]+:[a-z0-9]{32}/i) !== null)
{
console.log("It's valid, bloody fantastic!");
}
Obligatory JSFiddle.