import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?:(?<protocol>[a-z]+):\\/\\/)?\n"
+ "(?:(?:(?<username>[^@\\r\\n:]+))\n"
+ "(?::(?<password>[^@\\r\\n]+))?@)?\n"
+ "(?<host>[^\\/:\\r\\n]+)\n"
+ "(?::(?<port>\\d+))?\n"
+ "(?:\\/(?<path>[^?\\r\\n]+)?)?\n"
+ "(?:\\?(?<query>[^\\r\\n]+))?";
final String string = "http://server:12345/path/blabla\n"
+ "http://server.com:1234/path?query_string#fragment_id\n"
+ "ftp://user:password@server:1234/path\n"
+ "ftp://user@server:1234/path\n"
+ "http://www.server.com\n"
+ "www.server.com/path\n"
+ "server.com\n"
+ "http://user@server.com:1234/path?query_string#fragment_id\n"
+ "user@server.com:1234\n";
final Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS | Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html