import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?P<scheme>http(?:s)?:\\/\\/)?(?P<www>www\\d?\\.)?(?P<domain>\\b(?!www\\d?\\.)[a-z\\d\\-]+(?:\\.[a-z\\d\\-]{2,})+)(?P<port>:\\d{1,5})?(?P<path>\\/(?:[-a-zA-Z0-9._~!$&\\'()*+,;=:@]|%[0-9a-fA-F]{2})*)*(?P<query_fragm>[?#&][\\/\\_\\-\\&\\%\\?\\#\\+\\=\\.:a-zA-Z\\d]*)*$";
final String string = "http://example.com\n"
+ "https://www.example.com\n"
+ "http://example.com/path\n"
+ "https://www.example.com/path\n"
+ "http://example.com/path?query=1\n"
+ "https://www.example.com/path?query=1\n"
+ "http://example.com/path#fragment\n"
+ "https://www.example.com/path#fragment\n"
+ "http://example.com:8080\n"
+ "https://www.example.com:8080\n"
+ "http://subdomain.example.com\n"
+ "https://www.subdomain.example.com\n"
+ "http://subdomain.example.com/path\n"
+ "https://www.subdomain.example.com/path\n"
+ "http://subdomain.example.com/path?query=1\n"
+ "https://www.subdomain.example.com/path?query=1\n"
+ "http://subdomain.example.com/path#fragment\n"
+ "https://www.subdomain.example.com/path#fragment\n"
+ "http://subdomain.example.com:8080\n"
+ "https://www.subdomain.example.com:8080\n"
+ "http://example.org\n"
+ "https://www.example.org\n"
+ "http://example.org/path\n"
+ "https://www.example.org/path\n"
+ "http://example.org/path?query=1\n"
+ "https://www.example.org/path?query=1\n"
+ "http://example.org/path#fragment\n"
+ "https://www.example.org/path#fragment\n"
+ "http://example.org:8080\n"
+ "https://www.example.org:8080\n"
+ "http://subdomain.example.org\n"
+ "https://www.subdomain.example.org\n"
+ "http://subdomain.example.org/path\n"
+ "https://www.subdomain.example.org/path\n"
+ "http://subdomain.example.org/path?query=1\n"
+ "https://www.subdomain.example.org/path?query=1\n"
+ "http://subdomain.example.org/path#fragment\n"
+ "https://www.subdomain.example.org/path#fragment\n"
+ "http://subdomain.example.org:8080\n"
+ "https://www.subdomain.example.org:8080\n"
+ "http://example.net\n"
+ "https://www.example.net\n"
+ "http://example.net/path\n"
+ "https://www.example.net/path\n"
+ "http://example.net/path?query=1\n"
+ "https://www.example.net/path?query=1\n"
+ "http://example.net/path#fragment\n"
+ "https://www.example.net/path#fragment\n"
+ "http://example.net:8080\n"
+ "https://www.example.net:8080";
final Pattern pattern = Pattern.compile(regex, 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