如何检测字符串是否包含java中的URL?

时间:2011-04-26 23:01:49

标签: java android string token tokenize

  

可能重复:
  Java-How to detect the presence of URL in a string.

我们假设我有字符串:

“我喜欢访问http://www.google.com和www.apple.com”

如何对此字符串进行标记,并确定该标记是否包含URL?

1 个答案:

答案 0 :(得分:3)

请参阅:http://download.oracle.com/javase/6/docs/api/java/net/URL.html

import java.net.URL;
import java.net.MalformedURLException;

// Replaces URLs with html hrefs codes
public class URLInString {
    public static void main(String[] args) {
        String s = args[0];
        // separete input by spaces ( URLs don't have spaces )
        String [] parts = s.split("\\s");

        // Attempt to convert each item into an URL.   
        for( String item : parts ) try {
            URL url = new URL(item);
            // If possible then replace with anchor...
            System.out.print("<a href=\"" + url + "\">"+ url + "</a> " );    
        } catch (MalformedURLException e) {
            // If there was an URL that was not it!...
            System.out.print( item + " " );
        }

        System.out.println();
    }
}

How to detect the presence of URL in a string获得