the matt jones website.‎ > ‎Java‎ > ‎

Finding URLs in Strings

Recently, I came across as situation where I wanted to find url's from Strings. A quick google gave me the answers as to the Regex to use and then there was just the simple task of putting it all together.
 
The below code shows how to find URL's from within a string. Copy and paste below into a new class file and the code is yours to keep. For your consideration, you could use the Matcher.start() and Matcher.end() methods to get the url, should you require this.
 
package com.narkie.sandpit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * @author Matthew Jones
 */
public class parseURL {
    public void parser(String inputString) {
       
        String REGEX =
  "(http|https)://([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
        Pattern jPattern = Pattern.compile(REGEX);
        Matcher jMatch = jPattern.matcher(inputString);
        Boolean found = false;
        while (jMatch.find()) {
            //System.out.println("Found a URL");
            found = true;
        }
        if (!found) {
            //System.out.println("Not Found");
        }
    }
}
Comments