Skip to content

Instantly share code, notes, and snippets.

@wfwei
Created July 6, 2013 12:34
Show Gist options
  • Save wfwei/5939767 to your computer and use it in GitHub Desktop.
Save wfwei/5939767 to your computer and use it in GitHub Desktop.
URL Regex Pattern
// Protocol : //[user: password]@host[:port]/path /[?query][#fragment]
public static Pattern UrlPatt = Pattern
.compile(
"(?<protocol>.*?)://(?<loginfo>(?<user>.*?):(?<pwd>.*?)@)?(?<host>[^/]+)(?:(?<path>/[^\\?#]*)(?<query>\\?[^#]+)?)?(?<frag>#.*)?",
Pattern.CASE_INSENSITIVE);
public static void testUrlPatt() {
String[] urls = {
"https://www.google.com.hk/search?q=named+group+regex+java&oq=named+group+regex+java&aqs=chrome.0.57.5777j0&sourceid=chrome&ie=UTF-8#abc",
"http://wfwei.github.io/posts/regex/#abc",
"ftp://wfw:wfw@10.214.52.10:9999/?raw" };
Matcher match;
for (String url : urls) {
match = UrlPatt.matcher(url);
if (match.find()) {
System.out
.format("-----------------------------\n"
+ "url:\t\t%s\nprotocol:\t%s\nloginfo:\t%s\nhost:\t\t%s\n"
+ "path:\t\t%s\nquery:\t\t%s\nfragment:\t%s\n\n",
match.group(), match.group("protocol"),
match.group("loginfo"), match.group("host"),
match.group("path"), match.group("query"),
match.group("frag"));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment