Sample code:
String Message="http://indianexpress.com/article/sports/football/mexico-holds-host-brazil-to-0-0-draw-at-world-cup/ http://indianexpress.com/article/sports/cricket/suresh-raina-surprised-by-stuart-binnys-performance/ http://indianexpress.com/article/sports/football/fifa-world-cup-every-match-is-like-a-final-for-us-says-andres-iniesta/"
ArrayList<String> forrmatted=pullLinks(Message);
for(int i=0;i<forrmatted.size();i++){
String temp=forrmatted.get(i).toString();
Message=Message.replace(temp, "["+temp+"]");
}
private ArrayList<String> pullLinks(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;
}
1.Message string contains three links.
2.Create pullLinks method to pull links from Message string.
3. In pullLinks method create regular expression for links.
4. Now check pattern from input using while loop.
5. And return arraylist of type string.
6. In formatted arraylist we get links.
There is another way to check string contain valid URL or not:
if(!URLUtil.isValidUrl(URL)){
System.out.println("Valid");
}else{
System.out.println("Invalid");
}
If you want to check single URL then above method is best.
But if you want to pull multiple links from string then use pullLinks method.
There is another way to check string contain valid URL or not:
if(!URLUtil.isValidUrl(URL)){
System.out.println("Valid");
}else{
System.out.println("Invalid");
}
If you want to check single URL then above method is best.
But if you want to pull multiple links from string then use pullLinks method.
Comments
Post a Comment