下面的正则表达式来自精彩的Mastering Regular Expressions书。如果您不熟悉自由间距/注释模式,我建议您熟悉它。
\b
# Match the leading part (proto://hostname, or just hostname)
(
# ftp://, http://, or https:// leading part
(ftp|https?)://[-\w]+(\.\w[-\w]*)+
|
# or, try to find a hostname with our more specific sub-expression
(?i: [a-z0-9] (?:[-a-z0-9]*[a-z0-9])? \. )+ # sub domains
# Now ending .com, etc. For these, require lowercase
(?-i: com\b
| edu\b
| biz\b
| gov\b
| in(?:t|fo)\b # .int or .info
| mil\b
| net\b
| org\b
| name\b
| coop\b
| aero\b
| museum\b
| [a-z][a-z]\b # two-letter country codes
)
)
# Allow an optional port number
( : \d+ )?
# The rest of the URL is optional, and begins with / . . .
(
/
# The rest are heuristics for what seems to work well
[^.!,?;"'<>()\[\]{}\s\x7F-\xFF]*
(?:
[.!,?]+ [^.!,?;"'<>()\[\]{}\s\x7F-\xFF]+
)*
)?
为了简要解释这个正则表达式(要获得完整的解释,请参阅本书) - URL 有一个或多个点分隔部分,以有限的最终位列表或两个字母的国家/地区代码 (.uk .fr ...) 结尾。此外,部件可以有任何字母数字字符或连字符“-”,但连字符不能是部件的第一个或最后一个字符。然后可能有一个端口号,然后是其余的。
要从网站中提取此内容,请访问http://regex.info/listing.cgi?ed=3&p=207 它来自第 3 版的第 207 页。
页面上写着“版权所有 © 2008 Jeffrey Friedl”,所以我不确定使用条件到底是什么,但我希望如果你拥有这本书,你可以使用它......我希望我是不违反规则把它放在这里。