프로그래밍/Java

[Java] URL인지 체크하기, URL 정규식

Lou Park 2021. 1. 8. 23:00

Java에서 String이 URL인지 판별하는 함수이다.

public static boolean isUrl(String text) {
Pattern p = Pattern.compile("^(?:https?:\\/\\/)?(?:www\\.)?[a-zA-Z0-9./]+$");
Matcher m = p.matcher(text);
if (m.matches()) return true;
URL u = null;
try {
u = new URL(text);
} catch (MalformedURLException e) {
return false;
}
try {
u.toURI();
} catch (URISyntaxException e) {
return false;
}
return true;
}