I have a string (URL) like this:
"https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp"
I need to extract the last part only i.e. 02_Cuppy_lol.webp.
How can I do that?
Thanks!
You can use substring() and lastIndexOf() here:
String value = completeString.substring(completeString.lastIndexOf("/") + 1);
You can split this text/url and get last part, for example:
String url = "https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] splittedUrl = url.split("/");
String lastPart = splittedUrl[splittedUrl.length()-1)];
you can use the method split().follow this example
public class Demo {
public static void main(String args[]){
String str ="https://www9.online-convert.com/dl/web2/download-file/248f2225-7ed3-48dd-a586-ac1390bbeaab/02_Cuppy_lol.webp";
String[] temp=str.split("/");
int lastIndex =temp.length-1;
String lastPart = temp[lastIndex];
System.out.println(lastPart);
}
}
Output-:
02_Cuppy_lol.webp
Related
I have to remove this.
String removeKey = "problem_keys";
Code
public class Solution {
public static void main(String args[]) {
String removeKey = "problem_keys";
String url = "{\"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;problem_keys:1,35,3,4,5,6,7,15,16,11,12,16;\";}";
StringBuffer sb = new StringBuffer(url);
removeKey(sb, removeKey);
System.out.println(sb.toString());
}
public static void removeKey(StringBuffer url, String removeKey) {
int sIndex = url.indexOf(removeKey);
while (url.charAt(sIndex) != ';') {
url.deleteCharAt(sIndex);
}
url.deleteCharAt(sIndex);
}
}
Expected output.
{"arrival_mode:Self Drop;schedule:2020-09-10;payment_mode:Pay Online;address_id:67052;problem_id:11;problem_name:Abnormal noise;first:2000;product_name:demo tc;category_name:selfby;brand_name:bpl;transaction_type:Request;type:Display;}";
Guessing you want also to remove the "values", using java 8:
String toRemove = Arrays.stream(url.split(";")).filter(part -> part.contains(removeKey)).findFirst().orElse("");
String newUrl = url.replace(toRemove, "");
System.out.println(newUrl);
Speaking about the delimeters you can consider adding ";" to the toRemove string in a conditional block.
If you're aim is only to get rid of the string removeKey you can just:
url.replace(removeKey, "");
I would go with this:
String removeKey = "problem_keys;";
url = url.replace(removeKey, "") // Replace the whole "problem_keys;" string with an empty string
This question already has answers here:
What is the fastest way to get the domain/host name from a URL?
(8 answers)
Closed 3 years ago.
Im trying to split URLs, for example https://stackoverflow.com/questions/ and take only stackoverflow.com. How can I do this in Java without using the built in function getHost()?
If you can put your URL into a String , there is this option :
public static void main(String []args){
String str ="https://stackoverflow.com/questions/";
String[] parts = str.split("/");
String part1 = parts[0]; //https:
String part2 = parts[1]; //'nothing'
String part3 = parts[2]; //stackoverflow.com
String part4 = parts[3]; //questions
}
One thing you can do is use String#replaceAll. I know it's not what you want but off the bat it's a decent way to do it.
String uri = "https://stackoverflow.com/questions/";
if (uri.contains("https://")) {
uri = uri.replaceAll("https://", "");
}
if (uri.contains("http://")) {
uri = uri.replaceAll("http://", "");
}
int indexOfBackwardsSlash = uri.indexOf("/");
if (indexOfBackwardsSlash != -1) {
uri = uri.substring(0, indexOfBackwardsSlash);
}
Use URI#getPath.
URI uri = URI.create("https...");
String path = uri.getPath();
You could also use regular expressions:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UrlRegex {
public static void main(String []args){
String url = "https://stackoverflow.com/questions/";
Pattern pat = Pattern.compile("//([^/]*)"); //match everything between "//" and "/"
Matcher m = pat.matcher(url);
if (m.find()) {
String hostname = m.group(1);
}
}
}
Here you go :
Pattern pattern = Pattern.compile("^(?:(?:http)s?://)?(?<hostGroup>[^/:]+).*");
Matcher matcher = pattern.matcher("https://stackoverflow.com/questions/");
if (matcher.matches()) {
System.out.println(matcher.group("hostGroup"));
} else {
System.out.println("Not found! Invalid URL ^^");
}
The above will find stackoverflow.com for the following urls strings :
https://stackoverflow.com/questions/
http://stackoverflow.com/questions/
stackoverflow.com/questions/
stackoverflow.com:80/questions/
stackoverflow.com/
stackoverflow.com
I guess that's for practicing regex ? Otherwise, prefer using the standard APIs whenever possible - (in your case URI#getHost() !)
Cheers!
If you are sure that you are getting the proper URL format than you can just substring it preferred places.
public static void main(String[] args) {
String url = "https://stackoverflow.com/questions/";
System.out.println(getHostFast(url));
}
public static String getHostFast(String url) {
String subbed = url.substring(url.indexOf('/') + 2);
return subbed.substring(0, subbed.indexOf('/'));
}
The error prof method would need to contain additional check (for example if the next '/' exists after dropping http://.
I'm trying to split a specific String of the format
0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;
in order to extract and save value01 and value02. How can I do this?
Here is what i tried so far:
//buffer contains a String like: "0001,0004,dd/mm/yy hh:mm:ss,01,18,750"
String string = new String(buffer,0,len);
String[] parts = string.split(",");
String temp = parts[5];
String lum = parts[6];
System.out.print(temp);
System.out.print(lum);
With this code I get ArrayIndexOutofBounds when running the program in Netbeans.
Image of error description
Also tried this method:
//buffer contains a String like: "0001,0004,dd/mm/yy hh:mm:ss,01,18,750"
String s= new String(buffer,0,len);
String aux = s + ",";
String[] dados = aux.split(",");
float valor1 = Float.parseFloat(dados[5]);
float valor2 = Float.parseFloat(dados[6]);
System.out.print(aux);
This:
String temp = parts[5];
String lum = parts[6];
Should be this:
String temp = parts[4];
String lum = parts[5];
Remember that arrays in Java are zero-based. So if you do this:
String[] parts = "0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02".split(",");
Then "0001" would be in parts[0], "0004" in parts[1], "value01" in parts[4] etc.
Achieving what you're trying to do is acutally pretty easy.
Assuming that your string really always looks like:
0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;
Just cut off the start of the string which you don't need and extract the values afterwards:
// This can be done in hundreds of ways, for the sake of simplicity i'll use substring
String s ="0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02;";
String cutOff = s.substring(31, s.length()-1);
String[] results = cutOff.split(",");
please find below code. It has just a bit modification in Andrew's code. Since we are storing the string after splitting into a String array and it's obvious that array index starts with 0. That's why in order to get value01 and value02, we should use index 4 and 5.
public class JavaApplication1
{
public static void main(String[] args)
{
String str="0001,0004,dd/mm/yy hh:mm:ss,01,value01,value02";
String [] strArr=str.split(",");
String temp=strArr[4];
String lum=strArr[5];
System.out.println(temp);
System.out.println(lum);
}
}
I have a requirement that i have to get a specific portion from a String i.e if i have java.lang.String i need to get the com field from the String i have done this
public class uu {
public static void main(String[] args) {
String domain = "www.xyzw.com";
String[] strArray = domain.split("\\.");
for (String str : strArray) {
System.out.println(str);
}
}
}
it is giving me three fields separately but i need the com only ..
someone help me
String s = domain.substring(domain.lastIndexOf(".")+1);
Consider inserting error checks for the case that the string does not contain .
String domain = "www.xyzw.com";
String[] strArray = domain.split("\\.");
System.out.println(strArray[2]);
You can do:
String r = strArray[strArray.length - 1];
Or:
String r = domain.substring(domain.lastIndexOf(".") + 1);
If you work with domains you could use Google Guava InternetDoMainNames class. It is very simple
InternetDomainName.from("www.xyzw.com").publicSuffix();
How to use:
https://code.google.com/p/guava-libraries/wiki/InternetDomainNameExplained
http://koziolekweb.pl/2014/03/30/pomocna-guava-informacje-o-domenie/ (with example - translation to english is posible)
I have data as follows:
String s = "foo.com^null^[]";
String s1 = "bar.com^null^[{\"seen_first\":1357882827,\"seen_last\":1357882827,\"_id\":\"93.170.52.31\",\"exclude_from_publication\":false,\"locked\":false,\"agent\":\"domain_export\",\"web_published\":true,\"version\":\"IPv4\"},{\"seen_first\":1357882827,\"seen_last\":1357882827,\"_id\":\"93.170.52.21\",\"exclude_from_publication\":false,\"locked\":false,\"agent\":\"domain_export\",\"web_published\":true,\"version\":\"IPv4\"}]";
And note that third field.. it can be either [] or a json array.
And I am trying to parse these fields..
Here is my current attempt.
public static void check(String s) {
String [] tokens = s.split("^");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
System.out.println(tokens[2]);
if (tokens[2].trim().equals("[]")) {
System.out.println("here--> " +true);
}
System.out.println("---------");
}
What am i doing wrong?
^ is a metacharacter in a regex, meaning "the start of the string". You need to escape it:
String [] tokens = s.split("\\^");