通过正则表达式对URL进行Java验证
String url = "https://my-company-08.vv.xyz.com/abc.svc/Abcdef(id='{0}',text='ABC.XYZ')?$query=xxxx&$format=xml";
答案 0 :(得分:3)
网址可能是具有许多possible variants的复杂动物。如果您编写自己的正则表达式解析器,则很可能无法涵盖所有情况。使用内置的URI或URL类为您完成...
private static boolean isValidUri(String candidate) {
try {
new URI(candidate);
return true;
} catch (URISyntaxException e) {
e.printStackTrace();
return false;
}
}
使用网址
private static boolean isValidUrl(String candidate) {
try {
new URL(candidate);
return true;
} catch (MalformedURLException e) {
e.printStackTrace();
return false;
}
}
您的特定语法错误....
// returns false, error at character 51 which is the first (
System.out.println(isValidUri("https://my-company-08.vv.xyz.com/abc.svc/Abcdef(id= '{sd54asds2f21sddf}',text='ABC.XYZ')?$query=myClient&$format=xml"));
// returns true without the (id= '{sd54asds2f21sddf}',text='ABC.XYZ') stuff
System.out.println(isValidUri("https://my-company-08.vv.xyz.com/abc.svc/Abcdef?$query=myClient&$format=xml"));