views:

62

answers:

3

greetings all i have a text that may contain links something like:

" hello..... visit us on http://www.google.com.eg, and for more info, please contact us on http://www.myweb.com/help"

and i want to find and replace any link with the following link

anyone knows how to do so ?

and i have another question is that how any website like stackoverflow detects the links in the posts like this one and highlights them so any one can click them and visit the link?

+4  A: 

Using the java.util.regex you can get URLs by finding everything that matches the regexp: https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?.

import java.util.regex.*;

Pattern pattern = Pattern.compile("https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE);
Matcher myMatcher = pattern.matcher(myStringWithUrls);
while (myMatcher.find()) {
    ...
}
Wernight
there's a compiler error on the expression ?
sword101
Yes sorry I forgot one line. Still you should have the general way to get it.
Wernight
newbie,little help please :( :(
sword101
I've added the missing line above.
Wernight
A: 

i found this regex but it don't get the request parameters, and i need some help in it

String originalString = "Please go to http://www.stackoverflow.com?s=1&n=2";
        String newString = originalString.replaceAll(
                "http://.+?(com|net|org)/{0,1}", "<a href=\"$0\">$0</a>");

System.out.println(newString);
sword101
If you mean to refine your question, consider editing it rather than posting an answer.
Wernight
That answer only includes the domain name without the URI and it also works only for some domains.
Wernight
A: 

I think regular expressions are too slow to find URLs in large Strings. You should try state-machines which are better and there is a good one called Automaton

KARASZI István