我从RSS Feed获取字符串,有时会包含指向YouTube视频的链接。我已经能够从字符串中解析URL了。
我希望在WebView内部将网址替换为“链接到视频”,但点击此链接时,它应使用YouTube链接。
目前我更换字符串,但点击此字符串后,系统会转发新字符串,而不是YouTube网址。
我的代码:
String description = fFeed.getItem(fPos).getDescription();
// get all links from the description string
ArrayList<String> links_in_string = retrieveLinks(description);
Log.d("debug", "All Links: " + links_in_string.toString());
// search for YouTube links
ArrayList<String> resList = new ArrayList<String>();
String searchString = "www.youtube.com/watch?v=";
for (String curVal : links_in_string) {
if (curVal.contains(searchString)) {
resList.add(curVal);
}
}
Log.d("debug", "YouTube Links: " + resList.toString());
// convert to single YouTube URL strings and replace
// them in the description string
Object[] mStringArray = resList.toArray();
for (int i = 0; i < mStringArray.length; i++) {
Log.d("string is", (String) mStringArray[i]);
description = description.replace((String) mStringArray[i],
"Link zum Video");
}
/**
* Retrieve all the links from the description string
* of the RSS Feed
*/
private ArrayList<String> retrieveLinks(String text) {
ArrayList<String> links = new ArrayList<String>();
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();
if (urlStr.startsWith("(") && urlStr.endsWith(")")) {
urlStr = urlStr.substring(1, urlStr.length() - 1);
}
links.add(urlStr);
}
return links;
}
更新
我必须每隔一次搜索字符串中出现的url。我试过这种方式,但现在它没有取代URL
// convert to single YouTube URL strings and replace
// them in the description string
Object[] mStringArray = resList.toArray();
for (int i = 0; i < mStringArray.length; i++) {
//replace every second URL by "Link zum Video"
StringBuffer sb = new StringBuffer();
Pattern p = Pattern.compile((String) mStringArray[i]);
Matcher m = p.matcher(description);
int count = 0;
while (m.find()) {
if (count++ % 2 != 0) {
m.appendReplacement(sb, "Link zum Video");
}
}
m.appendTail(sb);
description = sb.toString();
Log.d("debug", "Description with replaced link: " + description);
}
答案 0 :(得分:0)
我没有测试它,但是使用锚标签可能会起作用:
description = description.replace((String) mStringArray[i],
"<a href=\""+(String) mStringArray[i]+"\">Link zum Video</a>");
答案 1 :(得分:0)
我使用RegEx解决了它:
String pattern = "(<a href=\".*?\">).*?(</a>)";
description = description.replaceAll(pattern, "$1Link zum Video$2");