URL regex Java
URL regular expressions can be used to verify if a string has a valid URL format as well as to extract an URL from a string.
URL regex that starts with HTTP or HTTPS
HTTP and HTTPS URLs that start with protocol can be validated using the following regular expression
Pattern.compile("^https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$")
Enter a text in the input above to see the result
Example code in Java:
import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;
public class Main {
public static void main(String []args) {
// Validate URL
boolean isMatch = Pattern.compile("^https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$")
.matcher("")
.find();
System.out.println(isMatch); // prints true
// Extract date from a string
String[] matches = Pattern.compile("https?:\\/\\/(?:www\\.)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)")
.matcher("You can view more details at https://uibakery.io or just ping via email.")
.results()
.map(MatchResult::group)
.toArray(String[]::new);
System.out.println(Arrays.toString(matches)); // prints [https://uibakery.io]
}
}
URL regex that doesn’t start with HTTP or HTTPS
The regular expression to validate URL without protocol is very similar:
Pattern.compile("^[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&//=]*)$")
Enter a text in the input above to see the result
Example code in Java:
import java.util.regex.Pattern;
import java.util.regex.MatchResult;
import java.util.Arrays;
public class Main {
public static void main(String []args) {
// Validate URL without protocol
boolean isMatch = Pattern.compile("^[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)$")
.matcher("uibakery.io/contact")
.find();
System.out.println(isMatch); // prints true
// Extract URL without protocol from a string
String[] matches = Pattern.compile("[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)")
.matcher("You can view more details at uibakery.io or just ping via email.")
.results()
.map(MatchResult::group)
.toArray(String[]::new);
System.out.println(Arrays.toString(matches)); // prints [uibakery.io]
}
}
Notes on URL validation
The above-mentioned regular expressions only cover the most commonly used types of URLs with domain names. If you have some more complex cases you might need a different solution.