检查String是否包含Java / Android中的URL的最佳方法是什么?
问题描述:
检查String是否包含Java / Android中的URL的最佳方法是什么?最好的方法是检查字符串是否包含| .com | .net | .org | .info | .everythingelse |?或者有更好的方法吗?
What's the best way to check if a String contains a URL in Java/Android? Would the best way be to check if the string contains |.com | .net | .org | .info | .everythingelse|? Or is there a better way to do it?
网址输入到Android中的EditText中,它可以是粘贴的网址,也可以是手动输入的网址用户不想输入http:// ...我正在开发一个URL缩短应用程序。
The url is entered into a EditText in Android, it could be a pasted url or it could be a manually entered url where the user doesn't feel like typing in http://... I'm working on a URL shortening app.
答
最好的方法是使用正则表达式,如下所示:
Best way would be to use regular expression, something like below:
public static final String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$";
Pattern p = Pattern.compile(URL_REGEX);
Matcher m = p.matcher("example.com");//replace with string to compare
if(m.find()) {
System.out.println("String contains URL");
}