我想从android中的String解析url.示例String是
"This is a new message. The content of the message is in 'http://www.example.com/asd/abc' "
Run Code Online (Sandbox Code Playgroud)
我想http://www.example.com/asd/abc在不使用subString方法的情况下解析String中的url .
Alé*_*lho 32
用这个:
public static String[] extractLinks(String text) {
List<String> links = new ArrayList<String>();
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
String url = m.group();
Log.d(TAG, "URL extracted: " + url);
links.add(url);
}
return links.toArray(new String[links.size()]);
}
Run Code Online (Sandbox Code Playgroud)
ina*_*ruk 31
更新:
您可以使用正则表达式和Patterns.WEB_URL正则表达式来查找文本中的所有网址.
原版的:
你可以使用Uri.parse(String uriString)功能.
mp5*_*501 10
如果您解析链接是为了给它们设置样式,Linkify 是一个优雅的解决方案:
descriptionTextView.setText("This text contains a http://www.url.com")
Linkify.addLinks(descriptionTextView, Linkify.WEB_URLS);
Run Code Online (Sandbox Code Playgroud)
您还可以更改链接的默认颜色:
descriptionTextView.setLinkTextColor(ContextCompat.getColor(getContext(),
R.color.colorSecondary));
Run Code Online (Sandbox Code Playgroud)
结果如下所示:
是的可能.尝试使用以下代码示例
ArrayList retrieveLinks(String text) {
ArrayList links = new ArrayList();
String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
char[] stringArray1 = urlStr.toCharArray();
if (urlStr.startsWith("(") && urlStr.endsWith(")"))
{
char[] stringArray = urlStr.toCharArray();
char[] newArray = new char[stringArray.length-2];
System.arraycopy(stringArray, 1, newArray, 0, stringArray.length-2);
urlStr = new String(newArray);
System.out.println("Finally Url ="+newArray.toString());
}
System.out.println("...Url..."+urlStr);
links.add(urlStr);
}
return links;
}
Run Code Online (Sandbox Code Playgroud)
谢谢迪帕克