Regex returns string undefined

人走茶凉 提交于 2019-12-03 00:53:34

问题


I am trying to extract hash value from an magnet link but it returns undefined

var tesst = "magnet:?xt=urn:btih:2B78EDFDDC87DC9605FB285997A80B787888C194&"
var test = tesst.match(/magnet:\?xt=urn:btih:[a-z\d]{40}\&/im);
alert (test[1]);

I cant understand what I am doing wrong.


回答1:


just mark what you want with capturing group:

/^magnet:\?xt=urn:btih:([a-z\d]{40})\&$/im

Also I recomend to not use regexp here.
Try followed:

tesst.split(':')[3].slice(0, -1);

slice(0, -1) used for remove last '&', you can use any other method, like slice(0, 40), replace(/[^\w]/g, '') or any other.




回答2:


var test = tesst.match(/magnet:\?xt=urn:btih:([a-z\d]{40})\&/im);

You forgot the ( ) around the hash part.




回答3:


You need to include [a-z\d]{40} part inside a capturing group and you don't need to escape & symbol, because it isn't a regex meta character.

> var test = tesst.match(/magnet:\?xt=urn:btih:([a-z\d]{40})&/im);
undefined
> console.log(test[1])
2B78EDFDDC87DC9605FB285997A80B787888C194



回答4:


You can use this regex

/([^:]+)&$/

and use test[1]

console.log(str.match(/([^:]+)&$/)[1]);


来源:https://stackoverflow.com/questions/27380962/regex-returns-string-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!