Posts

Showing posts with the label java

Detect and extract url from a string?

We can get URL from the text or String. /** * Returns a list with all links contained in the input */ public static List < String > extractUrls ( String text ) { List < String > containedUrls = new ArrayList < String >(); String urlRegex = "((https?|ftp|gopher|telnet|file):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)" ; Pattern pattern = Pattern . compile ( urlRegex , Pattern . CASE_INSENSITIVE ); Matcher urlMatcher = pattern . matcher ( text ); while ( urlMatcher . find ()) { containedUrls . add ( text . substring ( urlMatcher . start ( 0 ), urlMatcher . end ( 0 ))); } return containedUrls ; } Example: List < String > extractedUrls = extractUrls ( "Welcome to https://stackoverflow.com/ and here is another link http://www.google.com/ \n which is a great search engine" ); for ( String url : extractedUrls ) { System . out . ...

how to get url from string in java code||

This code is represent by search URL from the giving string or text. It is basic Regex for doing here. this code is detected www or start with http. Now the code is giving below.---------- //Pull all links from the body for easy retrieval private ArrayList pullLinks(String text) { ArrayList links = new ArrayList(); String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(text); while(m.find()) { String urlStr = m.group(); if (urlStr.startsWith("(") &amp;&amp; urlStr.endsWith(")")) { urlStr = urlStr.substring(1, urlStr.length() - 1); } links.add(urlStr); } return links; }