How to remove a substring in java - java

I am receiving a file path with "xyz" appended to it. name would look like D:/sdcard/filename.docxyz
i am using the below code to remove xyz but it is not working. what is missing here ?
String fileExtension = path.substring(path.lastIndexOf(".")+1);
String newExtension= fileExtension;
newExtension.replace("xyz", "");
path.replace(fileExtension, newExtension);
return path;

What is missing is that you need to save the result of your operations. Strings are immutable in Java, and the results of all String manipulations are therefore returned in the form of a new String:
newExtension = newExtension.replace("xyz", "");
path = path.replace(fileExtension, newExtension);

String in java are immutable, and changes upon it never occurs in place, but every time a new string is returned,
newExtension = newExtension.replace("xyz", "");

You could also use replaceAll() with a regex.
public static void main(String[] args) {
String s = "D:/sdcard/filename.docxyz";
System.out.println(s.replaceAll("xyz$", "")); // $ checks only the end
}
O/P :
input : s = "D:/sdcard/filename.docxyz";
D:/sdcard/filename.doc
input : String s = "D:/sdcard/filenamexyz.docxyz";
output : D:/sdcard/filenamexyz.doc

newExtension.replace("xyz", "");
Will only return string which has "xyz" removed but newExtension will remain as it is. Simple fix for your problem is use as below
String newExtension= fileExtension.replace("xyz", "");

Related

Removing some patterns before a particular string using Java

I want to remove some patterns between two "/" from the string, for example:
Input
/DT_Gateway/gateway/ACC/input/..
Output
/DT_Gateway/gateway/ACC
I have tried writing this code, but getting an error. I am new to Java, please help.
public class cut {
public static void main(String[] args) {
String myString = "/DT_Gateway/gateway/ACC/input/..";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("/.."));
System.out.println(newString);
}
}
Note : this is a very custom solution to your problem, not a general way to do it .
String myString = "/DT_Gateway/gateway/ACC/input/..";
String newString = myString.substring(0, myString.indexOf("/i"));
System.out.println(newString);
Try this solution with regex:
"/DT_Gateway/gateway/ACC/input/..".replaceAll("(/[^/]+){2}$", "")
The regex is basically find two of the following pattern at the end of the string
/[^/]+
This means a forward slash followed by an unlimited number of non-forward-slashes.
It seems that relative paths should be normalized, XXX/.. removed.
That would go as follows
String myString = "/DT_Gateway/gateway/ACC/input/..";
System.out.println(myString.replaceAll("/[^/]+/\\.\\.(/|$)", "$1"));
String myString2 = "/DT_Gateway/gateway/ACC/input/../x.txt";
System.out.println(myString2.replaceAll("/[^/]+/\\.\\.(/|$)", "$1"));
Path path = Paths.get(myString);
System.out.println(path.normalize().toString());
Path path2 = Paths.get(myString2);
System.out.println(path2.normalize().toString());
/DT_Gateway/gateway/ACC
/DT_Gateway/gateway/ACC/x.txt
/DT_Gateway/gateway/ACC
/DT_Gateway/gateway/ACC/x.txt
Java Path is - for (all kinds of) file systems - quite the tool.
Especially as there is XXX/../..

Using regular expressions to rename a string

In java, I want to rename a String so it always ends with ".mp4"
Suppose we have an encoded link, looking as follows:
String link = www.somehost.com/linkthatIneed.mp4?e=13974etc...
So, how do I rename the link String so it always ends with ".mp4"?
link = www.somehost.com/linkthatIneed.mp4 <--- that's what I need the final String to be.
Just get the string until the .mp4 part using the following regex:
^(.*\.mp4)
and the first captured group is what you want.
Demo: http://regex101.com/r/zQ6tO5
Another way to do this would be to split the string with ".mp4" as a split char and then add it again :)
Something like :
String splitChar = ".mp4";
String link = "www.somehost.com/linkthatIneed.mp4?e=13974etcrezkhjk"
String finalStr = link.split(splitChar)[0] + splitChar;
easy to do ^^
PS: I prefer to pass by regex but it ask for more knowledge about regex ^^
Well you can also do this:
Match the string with the below regex
\?.*
and replace it with empty string.
Demo: http://regex101.com/r/iV1cZ8
Try below code,
private String trimStringAfterOccurance(String link, String occuranceString) {
Integer occuranceIndex = link.indexOf(occuranceString);
String trimmedString = (String) link.subSequence(0, occuranceIndex + occuranceString.length() );
System.out.println(trimmedString);
return trimmedString;
}

How to Check filename

I have a method that reads filename for a file from a certain source. My method should handle two types of files. My next method depends on the name of the file.
_InPayed.txt" "_OutPayed.txt
My problem is how to check if the filename is ..._inpayed Or ..._OutPayed
How to check the string after the strick " _"
Code:
public class FilenameDemo {
public static void main(String[] args) {
final String FPATH = "/home/mem/"filename.txt";
System.out.println("Extension = " + myHomePage.extension());
System.out.println("Filename = " + myHomePage.filename());
}
}
No need for subString. A simple call to contains(...) is all you need. More importantly, learn to use the API.
if (myString.toLowerCase().contains("inpayed")) {
// do something
}
String API
If you want to check the certain string in the file name then use contains method.
&
You can get the file name after _ using below expression
System.out.println("Filename = "+FPATH.substring(FPATH.lastIndexOf("_")+1,FPATH.lastIndexOf(".")));
The string must contain one and only one _ for this to work.
String fullFile="whatever_InOutPayed.txt"
String[] split = file.split("_");
// split[0] = "whatever"
// split[1] = "InOutPayed.txt"
String file = split[1];
If it contains more than one then take the last element of the array
String file = split[split.length - 1];
or you can easily use String.contains().
You can use substring() method to extract a desired part of a file name stored as String. Or if the part you are checking will always be at the end of the String a simpler option is to use endsWith(). Check the documentation for details about the method usage.

Query regarding regular expression

hi I have a string like this:
String s = "#Path(\"/BankDBRestService/customerExist(String")\";
I want to make that string as
#Path("/BankDBRestService/customerExist")
I tried this:
String foo = s.replaceAll("[(](.*)", "");
i am getting output as
#Path
can anyone please provide me the reqular expression to make this work
Try this one :
String s = "#Path(\"/BankDBRestService/customerExist(String\")";
String res = s.replaceAll("[(]([a-zA-Z_])+", "");
System.out.println(res);
Output : #Path("/BankDBRestService/customerExist")
If your string is "#Path(\"/BankDBRestService/customerExist(String)\")" i.e. with closed parenthesis then use regex [(]([a-zA-Z_])+[)]
try this
String foo = s.replaceAll("(.*)\\(.*\\)", "$1");

Problem in replacing special characters in a String in java

I got a String as response from server which is like the below:
hsb:\\\10.217.111.33\javap\Coventry\
Now I want to parse this string in such a way that I need to replace all \ with /.
Also I need to remove the first part of the String which is hsb:\\\
So, my resultant string should be of like this :
10.217.111.33/javap/coventry/
Can anyone help me by providing sample java code for this problem.
Here you have a "dirty" startup "solution":
String s = "hsb:\\\\\\10.217.111.33\\javap\\Coventry\\";
String w = s.replace('\\', '/');
String x = w.replace("hsb:///", "");
String result = yourString.substring(7);
result = result.replaceAll("\\\\", "/");

Categories

Resources