Mahmoud Saleh
Mahmoud Saleh

Reputation: 33605

How to detect links in a text?

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?

Upvotes: 1

Views: 1042

Answers (2)

KARASZI István
KARASZI István

Reputation: 31467

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

Upvotes: 0

Wernight
Wernight

Reputation: 37620

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()) {
    ...
}

Upvotes: 4

Related Questions