regex url problem
i'm using this regex
((?:https?://|www\d{0,3}[.]|[a-z0-9.\-开发者_StackOverflow中文版]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'\".,<>?«»“”‘’]))
to match urls (found here http://daringfireball.net/2010/07/improved_regex_for_matching_urls it's the bottom one) and when i use match in actionscript 3 it returns the link and everything after it, so if I tried this 'hello http://www.apple.com world' it will return 'http://www.apple.com world' how do I JUST get the url and not the 'world' part.
This works for me:
var match = "hello http://www.apple.com world".match(/\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i)
as does this:
var match = "hello http://www.apple.com world".match(new RegExp(
"\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)"+
"(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\s()<>]+\\)))*\\))+"+
"(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|"+
"[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))",
"i" // case insensitive
));
Just remember the string quoting rules. If you quote your regexp with //
like the first example then you need to backslash escape literal /
. If you quote your regexp with ""
then you need to backslash escape all "
and \
because the backsalsh itself has meaning within strings.
Also, remember that the URL is caught in the first capture group which you can access with:
if (match) {
url = match[1];
}
or if you supply the global flag g
then the matches will be an array of all captured URLs.
精彩评论