Wil*_* L. 19 java string android
检查String是否包含Java/Android中的URL的最佳方法是什么?最好的方法是检查字符串是否包含| .com | .net | .org | .info | .everythingelse |?或者有更好的方法吗?
该网址输入到Android中的EditText中,它可以是粘贴的网址,也可以是手动输入的网址,用户不想输入http:// ...我正在处理网址缩短应用.
Cha*_*dra 30
最好的方法是使用正则表达式,如下所示:
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");
}
Run Code Online (Sandbox Code Playgroud)
这只是通过构造函数周围的try catch完成(这是必要的).
String inputUrl = getInput();
if (!inputUrl.contains("http://"))
inputUrl = "http://" + inputUrl;
URL url;
try {
url = new URL(inputUrl);
} catch (MalformedURLException e) {
Log.v("myApp", "bad url entered");
}
if (url == null)
userEnteredBadUrl();
else
continue();
Run Code Online (Sandbox Code Playgroud)
环顾四周后,我尝试通过删除try-catch块来改善Zaid的答案。此外,此解决方案使用正则表达式可识别更多模式。
因此,首先获得以下模式:
// Pattern for recognizing a URL, based off RFC 3986
private static final Pattern urlPattern = Pattern.compile(
"(?:^|[\\W])((ht|f)tp(s?):\\/\\/|www\\.)"
+ "(([\\w\\-]+\\.){1,}?([\\w\\-.~]+\\/?)*"
+ "[\\p{Alnum}.,%_=?&#\\-+()\\[\\]\\*$~@!:/{};']*)",
Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
Run Code Online (Sandbox Code Playgroud)
然后,使用此方法(假设str是您的字符串):
// separate input by spaces ( URLs don't have spaces )
String [] parts = str.split("\\s+");
// get every part
for( String item : parts ) {
if(urlPattern.matcher(item).matches()) {
//it's a good url
System.out.print("<a href=\"" + item + "\">"+ item + "</a> " );
} else {
// it isn't a url
System.out.print(item + " ");
}
}
Run Code Online (Sandbox Code Playgroud)