这是LinkedIn的开源URL-Detector网址解析工具。对于Url网址:http://user@example.com:39000/hello?boo=fffrag,使用该开源URL检测器可以解析得到如下部分:
Scheme – "http" 用户名 – "user" 密码 – null 主机 – "[author]example[/author].com" 端口 – 39000 路径 – "/hello" 查询 – "?boo=ff" 片段 – "frag"
|
该库解析URL的功能非常强大,强于如下简单的正则表达式:
(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))? 或 ((ftp|http|https):\/\/)?(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))? 或 ((((f|ht)tps?:)?//)?([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~]+(:[^ @:]+)?@)?((([a-zA-Z0-9\\-]{1,255}|xn--[a-zA-Z0-9\\-]+)\\.)+(xn--[a-zA-Z0-9\\-]+|[a-zA-Z]{2,6}|\\d{1,3})|localhost|(%[0-9a-fA-F]{2})+|[0-9]+)(:[0-9]{1,5})?([/\\?][^ \\s/]*)*)
|
从最后一个正则表达式看到,正则越强大,越复杂,越难以维护,如同天书。使用URL-Detector的性能要比正则表达式提高很多很多。
URL-Detector能够支持Html5 scheme以及Email和IPv4和Ipv6地址的RFC校验与解析。
使用很简单:
import com.linkedin.urls.detection.UrlDetector; import com.linkedin.urls.detection.UrlDetectorOptions; ... UrlDetector parser = new UrlDetector("hello this is a url Linkedin.com", UrlDetectorOptions.Default); List<Url> found = parser.detect();
for(Url url : found) { System.out.println("Scheme: " + url.getScheme()); System.out.println("Host: " + url.getHost()); System.out.println("Path: " + url.getPath()); }
|
Github项目
Open Sourcing URL-Detector: A Java Library to Dete