code_junkie

How to detect the presence of URL in a string

Nov 12th, 2011
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. import java.net.URL;
  2. import java.net.MalformedURLException;
  3.  
  4. // Replaces URLs with html hrefs codes
  5. public class URLInString {
  6. public static void main(String[] args) {
  7. String s = args[0];
  8. // separete input by spaces ( URLs don't have spaces )
  9. String [] parts = s.split("\s");
  10.  
  11. // Attempt to convert each item into an URL.
  12. for( String item : parts ) try {
  13. URL url = new URL(item);
  14. // If possible then replace with anchor...
  15. System.out.print("<a href="" + url + "">"+ url + "</a> " );
  16. } catch (MalformedURLException e) {
  17. // If there was an URL that was not it!...
  18. System.out.print( item + " " );
  19. }
  20.  
  21. System.out.println();
  22. }
  23. }
  24.  
  25. "Please go to http://stackoverflow.com and then mailto:[email protected] to download a file from ftp://user:pass@someserver/someFile.txt"
  26.  
  27. Please go to <a href="http://stackoverflow.com">http://stackoverflow.com</a> and then <a href="mailto:[email protected]">mailto:[email protected]</a> to download a file from <a href="ftp://user:pass@someserver/someFile.txt">ftp://user:pass@someserver/someFile.txt</a>
  28.  
  29. url.getProtocol();
  30.  
  31. (?bhttp://[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]
  32.  
  33. if (s.StartsWith("(") && s.EndsWith(")"))
  34. {
  35. return s.Substring(1, s.Length - 2);
  36. }
  37.  
  38. String originalString = "Please go to http://www.stackoverflow.com";
  39. String newString = originalString.replaceAll("http://.+?(com|net|org)/{0,1}", "<a href="$0">$0</a>");
  40.  
  41. String msg = "Please go to http://stackoverflow.com";
  42. String withURL = msg.replaceAll("(?:https?|ftps?)://[\w/%.-]+", "<a href='$0'>$0</a>");
  43. System.out.println(withURL);
Add Comment
Please, Sign In to add comment