ReplaceAll Method - java

I want to replace "\" with this "/" in my string.
I am using method replaceAll for this. But it is giving me error.
String filePath = "D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg";
String my_new_str = filePath.replaceAll("\\", "//");

Just use replace.
The method replaceAll takes a regular expression and yours would be malformed.
String filePath = "D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg";
System.out.println(filePath.replace("/", "\\"));
Output
D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg

When you absolutely want to use regex for this, use:
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg";
String my_new_str = filePath.replaceAll("\\\\", "/");
Output of my_new_str would be:
D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg
Just be sure to notice the double backslashes \\ in the source String (you used single ones \ in your question.)
But Mena showed in his answer a much simpler, more readable way to achive the same. (Just adopt the slashes and backslashes)

You are unable because character '//' should be typed only single '/'.
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\", "/");
Above may be fail during execution giving you a PatternSyntaxException, because the first String is a regular expression so you use this,
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\\\", "/");
Check this Demo ideOne

Related

Split a string in java based on custom logic

I have a string
"target/abcd12345671.csv"
and I need to extract
"abcd12345671"
from the string using Java. Can anyone suggest me a clean way to extract this.
Core Java
String fileName = Paths.get("target/abcd12345671.csv").getFileName().toString();
fileName = filename.replaceFirst("[.][^.]+$", "")
Using apache commons
import org.apache.commons.io.FilenameUtils;
String fileName = Paths.get("target/abcd12345671.csv").getFileName().toString();
String fileNameWithoutExt = FilenameUtils.getBaseName(fileName);
I like a regex replace approach here:
String filename = "target/abcd12345671.csv";
String output = filename.replaceAll("^.*/|\\..*$", "");
System.out.println(output); // abcd12345671
Here we use a regex alternation to remove all content up, and including, the final forward slash, as well as all content from the dot in the extension to the end of the filename. This leaves behind the content you actually want.
Here is an approach with using regex
String filename = "target/abcd12345671.csv";
var pattern = Pattern.compile("target/(.*).csv");
var matcher = pattern.matcher(filename);
if (matcher.find()) {
// Whole matched expression -> "target/abcd12345671.csv"
System.out.println(matcher.group(0));
// Matched in the first group -> in regex it is the (.*) expression
System.out.println(matcher.group(1));
}

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;
}

Giving inputs to java regex

I have a regex like below one :
"\\t'AUR +(username) .*? /ROLE=\"(my_role)\".*$"
username and my_role parts will be given from args. So they always change when the script is starting. So how can i give parameters to that part of regex ?
Thanks for your helps.
Define regex like this:
String fmt = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
// assuming userName and myRole are your arguments
String regex = String.format(fmt, userName, myRole);
You should escape special characters in dynamic strings using Pattern.quote. To put the regex parts together you can simply use string concatenation like this:
String quotedUsername = Pattern.quote(username);
String quotedRole = Pattern.quote(my_role);
String regexString = "\\t'AUR +(" + quotedUsername +
") .*? /ROLE=\"(" + quotedRole + ")\".*$";
I think mixing regular expressions with format strings when using String.format can make the regex harder to understand.
Use string format or straight string concat to construct the regex before passing it to compile ...
Try this for an example:
String patternString = "\\t'AUR +(%s) .*? /ROLE=\"(%s)\".*$";
String formatted = String.format(patternString, username,my_role);
System.out.println(formatted);
Pattern pattern = Pattern.compile(patternString);
You can run a working example here: http://ideone.com/93YeNg

String manipulation questions

I have a string like "C:\Program Files\Directory\Something.txt" and I would like to convert it into "C:\\Program Files\\Directory\\Something.txt" So basically add \ wherevever a \ is found. Is the best way to approach this using indexOf and breaking the string into sustrings and then concatenating again or is there a more efficent way of doing this in Java?
String s = "C:/Program Files/Directory/Something.txt";
String s2 = s.replaceAll("/", "//");
// => "C://Program Files//Directory//Something.txt"
[Edit]
If the string has backslashes then it gets really fun since that is the regular expression escape character. This should work:
String s = "C:\\Program Files\\Directory\\Something.txt";
s.replaceAll("\\\\", "\\\\\\\\");
// => "C:\\\\Program Files\\\\Directory\\\\Something.txt"
Note that's four backslashes in the regex (two pairs in sequence to get two literal backslashses) and then eight in the replacement string since backslashes are also escape characters for literal strings.
You could use the File.separator property to make it more cross-platform:
String input = "C:/Program Files/Directory/Something.txt";
String result = input.replaceAll(File.separator, File.separator + File.separator);
You can just use String.replaceAll for this.
String str = "C:/Program Files/Directory/Something.txt";
str = str.replaceAll("/","//");
String s = "C:/Program Files/Directory/Something.txt";
s = s.replace("/", "//");
This will replace all / in the string with //

Categories

Resources