Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How find anchor Link from String?

I am new in Android now want how find anchor link tag from strings for example I have string like this which have some discrption and link

string product_distription="Buy this awesome " Thumb Design Mobile OK Stand Holder Universal For All 
here input
<a href="http://stackoverflow.com" >Buy now</a>

"
ouput: http://stackoverflow.com

Now only want extract link only from this string becuase I have app which have descrption link coming from PHP & MySQL and show in Android textview with link so now I only want know if discrption including any HTML anchor tag it will extract from the discrption only can extract not whole discrption only show this link

like image 854
joshua Avatar asked Jan 20 '26 09:01

joshua


1 Answers

You can do it as follows:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(extractAnchorLinks(
                "This <a href=\"www.google.com\">search engine</a> is the most popular. This <a href=\"www.stackoverflow.com\"> website is the largest online community for developers</a>There are millions of websites today"));
    }

    public static List<String> extractAnchorLinks(String string) {
        List<String> anchorLinkList = new ArrayList<String>();
        final String TAG = "a href=\"";
        final int TAG_LENGTH = TAG.length();
        int startIndex = 0, endIndex = 0;
        String nextSubstring = "";
        do {
            startIndex = string.indexOf(TAG);
            if (startIndex != -1) {
                nextSubstring = string.substring(startIndex + TAG_LENGTH);
                endIndex = nextSubstring.indexOf("\">");
                if (endIndex != -1) {
                    anchorLinkList.add(nextSubstring.substring(0, endIndex));
                }
                string = nextSubstring;
            }
        } while (startIndex != -1 && endIndex != -1);
        return anchorLinkList;
    }
}

Output:

[www.google.com, www.stackoverflow.com]

The logic is straight forward. Moreover, the variable names are also self-explantory. Nevertheless, feel free to comment in case of any doubt.

like image 106
Arvind Kumar Avinash Avatar answered Jan 22 '26 23:01

Arvind Kumar Avinash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!