import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^https?:\\/\\/((?:[a-z0-9]-?)+[^-\\.]\\.)?(?:[a-z0-9]-?)+[^-\\.]\\.[a-z]{2,15}(?:\\.[a-z]{2})?$";
final String string = "######################## Match\n"
+ "http://www.example.co.sa\n"
+ "http://www.some-domain-name.com\n"
+ "http://WWW.EXAMPLE.NET\n"
+ "http://www.google.com\n"
+ "http://www.some-site.engineering\n"
+ "https://www.google.com\n"
+ "http://www.efg-cba.asdfgh\n"
+ "https://some-sub-domain.exam-ple.musem.uk\n"
+ "http://sub-domain.example-site.engineering\n"
+ "http://test-www.mi-creativity.com\n"
+ "https://google.co.in\n"
+ "http://maps.google.com\n"
+ "http://abc.site-name.com\n"
+ "http://google.com\n\n"
+ "######################## NO Match\n"
+ "www.google\n"
+ "www.google.com\n"
+ "mail.google.com\n"
+ "://www.google\n"
+ "//www.google\n"
+ ":google.com\n"
+ "http://www..google.co.sa\n"
+ "http://www.google..co.uk\n"
+ "http://www.google.co..uk\n"
+ "htt:google.com\n"
+ "http:google.com\n"
+ "http:/google.com\n"
+ "http//www.google.com\n"
+ "http://www.go ogle.com\n"
+ "http://www.google.c om\n"
+ "http://abc.-google.com \n"
+ "http://efg.g--oogle.com \n"
+ "http://xyz.google-.com\n"
+ "http://abc.-google.com\n"
+ "http://efg.g--oogle.com\n"
+ "http://cba.example.c\n"
+ "http://lm.example.co.i\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.CASE_INSENSITIVE);
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