开发者

How can I detect if a string contains a URL in java? [duplicate]

开发者 https://www.devze.com 2023-02-28 18:08 出处:网络
This question already has answers here: 开发者_开发百科 Closed 11 years ago. Possible Duplicate: Java-How to detect the presence of URL in a string.
This question already has answers here: 开发者_开发百科 Closed 11 years ago.

Possible Duplicate:

Java-How to detect the presence of URL in a string.

Let's assume I have the string:

"I like visiting http://www.google.com and www.apple.com"

How can I tokenize this string, and determine if the token contains a URL?


Please see: 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();
    }
}

Obtained from, How to detect the presence of URL in a string

0

精彩评论

暂无评论...
验证码 换一张
取 消