MENU

Convert URLs in Java strings to links

TOC

Java (computer) regular expressionin a string usinguniform resouce locatorindicates object of desire, like, hate, etc.link(Convert to (a href=...)

in a string in Java.uniform resouce locatorusing a regular expression,link(a href=...)conversionThe following is a sample source that will be used.

source code

/** regular expression pattern for extracting URL */
public static final Pattern convURLLinkPtn =
    Pattern.compile
    ("(http://|https://){1}[\\w\. \\-/:\\#\? \\=\\&\\\;\\%\\~\\+]+",
    Pattern.CASE_INSENSITIVE);

/**
 * URLs in the specified string, using regular expressions,
 * link (a href=...) to a link (a href=...) using a regular expression.
 * @param str Specified string.
 * @return String converted to a link.
 */
public static String convURLLink(String str) {
    Matcher matcher = convURLLinkPtn.matcher(str);
    return matcher.replaceAll("<a href="/en/\"$0\"/">$0</a>");
}


Execution Result

◆Example of Execution

public static void main(String[] args) {
    // simple pattern
    String ret1 = convURLLink("https://chat-messenger.com/");
    System.out.println(ret1);

    // This can be used for patterns with complex URLs embedded in the string.
    String ret2 = convURLLink("Hello." +
            "http://aaa.co.jp/sup/topic.py?dep_id=108&~id=108" +
            "Visit the URL here.") ;
    System.out.println(ret2);
}

◆Output result

<a href="/en/”https://chat-messenger.com/”/">https://chat-messenger.com/</a>

Hello.<a http:>http://aaa.co.jp/sup/topic.py?dep_id=108&~id=108</a>Go to the URL here.

TOC