I want to parse the url from a String in android. The example String is
"This is a new message. The content of the message is in 'http://www.example.com/asd/abc' "
I want to parse the url http://www.example.com/asd/abc
from the String without using the subString method.
URL parsing is a function of traffic management and load-balancing products that scan URLs to determine how to forward traffic across different links or into different servers. A URL includes a protocol identifier (http, for Web traffic) and a resource name, such as www.microsoft.com.
Spaces are not allowed in URLs. They should be replaced by the string %20. In the query string part of the URL, %20 can be abbreviated using a plus sign (+).
The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods: getProtocol. Returns the protocol identifier component of the URL.
Use this:
public static String[] extractLinks(String text) {
List<String> links = new ArrayList<String>();
Matcher m = Patterns.WEB_URL.matcher(text);
while (m.find()) {
String url = m.group();
Log.d(TAG, "URL extracted: " + url);
links.add(url);
}
return links.toArray(new String[links.size()]);
}
Updated:
You can use regular expression with Patterns.WEB_URL
regular expression to find all urls in your text.
Original:
You can use Uri.parse(String uriString)
function.
If you are parsing the links for the purpose of styling them, Linkify is an elegant solution:
descriptionTextView.setText("This text contains a http://www.url.com")
Linkify.addLinks(descriptionTextView, Linkify.WEB_URLS);
You can also change the default colour of the link:
descriptionTextView.setLinkTextColor(ContextCompat.getColor(getContext(),
R.color.colorSecondary));
The result looks like this:
Yes its possible. Try with the following code sample
ArrayList retrieveLinks(String text) {
ArrayList links = new ArrayList();
String regex = "\\(?\\b(http://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(text);
while(m.find()) {
String urlStr = m.group();
char[] stringArray1 = urlStr.toCharArray();
if (urlStr.startsWith("(") && urlStr.endsWith(")"))
{
char[] stringArray = urlStr.toCharArray();
char[] newArray = new char[stringArray.length-2];
System.arraycopy(stringArray, 1, newArray, 0, stringArray.length-2);
urlStr = new String(newArray);
System.out.println("Finally Url ="+newArray.toString());
}
System.out.println("...Url..."+urlStr);
links.add(urlStr);
}
return links;
}
Thanks Deepak
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With