开发者

Regular expression to find URLs but not include punctuation AFTER the URL

Example: "My site is http://www.abcd.com, and yours is http://www.def.ghi/jkl. Is Fred's https://www.xyz.com? Or is it http://www.xxx.com?abc=def? (I thought his site was http://www.mmm.com), but clearly it's not."

This should extract

http://www.abcd.com http://www.def.ghi/jkl https://www.xyz.com http://www.xxx.com?abc=def http://www.mmm.com

Notes: it should assume that any punctuation following the url is NOT part of the url, e.g. the comma after http://www.abcd.com, is开发者_JAVA技巧 not part of the url. This includes trailing question marks, which I realize in actuality COULD be part of the url. Of course, if a question mark is followed by querystring data, it SHOULD be considered part of the url. Note that urls might be followed by multiple punctuation marks, as in the the case of (Is your url http://abcd.com)?

Urls (and their trailing punctuation, if any) will always be followed by a space, a newline/return character -- or they'll be the end of the string being tested.

The will be preceded by a whitespace character or, possibly, an open bracket or parenthesis, as in "Please visit my site (http://www.abcd.com)." Or they'll come at the beginning of the string.

This regexp should work for http, https and ftp.

This is for an Actionscript project. I believe that Actionscript uses the same regular-expression engine as Javascript.

Thanks!


Have a look here: http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/

EDIT: shanethehat and divillysausages also mentioned this link: http://gskinner.com/RegExr/ which I hadn't seen before and which features online evaluation (in other words, you can tune your regex without firing up your coding IDE, which is awesome). Thanks!


First off, rolling your own regexp to parse URLs is a terrible idea. You must imagine this is a common enough problem that someone has written, debugged and tested a library for it, according to the RFCs. There are a ton of edge cases when it comes to parsing URLs: international domain names, actual (.museum) vs. nonexistent (.jpg) URLs, weird punctuation including parentheses, punctuation at the end of the URL etc.

I've looked at a ton of libraries, and they all have their downsides. See a comparison of JavaScript URL parsing libraries here.

If you want a regular expression, the one in Component is quite comprehensive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜