String manipulation questions - java

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 //

Related

Java: Can't remove backslash when appending to a string

I'm creating a string representation of a file path. I'm working on a Windows machine.
The end result should look like this:
C:\Users\this_is_me\workarea\Myapp\myapp\props\
Instead it looks like this:
C:\Users\this_is_me\workarea\Myapp\myapp\\props\
The error is that second backslash before props. I think that this error is occurring because \p might be a regex expression?
Here is the code where I create the string:
private final static String APP_HOME = "\\workarea\\Myapp\\myapp\\";
private final static String PROPS_HOME = "\\props\\";
public static String getPropsPath() {
String propsHome = null;
String userHome = System.getProperty("user.home");
propsHome = userHome + APP_HOME + PROPS_HOME;
return propsHome;
}
I tried using a StringBuilder and I still get the same result.
Just remove the extra backslash after APP_HOME:
private final static String APP_HOME = "\\workarea\\Myapp\\myapp";
private final static String PROPS_HOME = "\\props\\";
propsHome = userHome + APP_HOME + PROPS_HOME;
System.out.println(propsHome);
Output:
C:\Users\this_is_me\workarea\Myapp\myapp\props\
APP_HOME ends with \ and PROPS_HOME starts with \, so you get it twice.
If you really want to build paths this way, remove one these backslashes. But should also have a look at the File and Path classes, which are better suited for these kind of things.
Looks like APP_HOME ends with backslash and PROPS_HOME starts with backslash, therefore you get double backlash as a result of concatenation.
Since the first letter of PROPS_HOME starts with \ and the end of APP_HOME is \ you get it twice,
propsHome = userHome + APP_HOME + PROPS_HOME.substring(1);

ReplaceAll Method

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

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

Splitting String using split method

I want split a string like this:
C:\Program\files\images\flower.jpg
but, using the following code:
String[] tokens = s.split("\\");
String image= tokens[4];
I obtain this error:
11-07 12:47:35.960: E/AndroidRuntime(6921): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:
try
String s="C:\\Program\\files\\images\\flower.jpg"
String[] tokens = s.split("\\\\");
In java(regex world) \ is a meta character. you should append with an extra \ or enclose it with \Q\E if you want to treat a meta character as a normal character.
below are some of the metacharacters
<([{\^-=$!|]})?*+.>
to treat any of the above listed characters as normal characters you either have to escape them with '\' or enclose them around \Q\E
like:
\\\\ or \\Q\\\\E
You need to split with \\\\, because the original string should have \\. Try it yourself with the following test case:
#Test
public void split(){
String s = "C:\\Program\\files\\images\\flower.jpg";
String[] tokens = s.split("\\\\");
String image= tokens[4];
assertEquals("flower.jpg",image);
}
There is 2 levels of interpreting the string, first the language parser makes it "\", and that's what the regex engine sees and it's invalid because it's an escape sequence without the character to escape.
So you need to use s.split("\\\\"), so that the regex engine sees \\, which in turn means a literal \.
If you are defining that string in a string literal, you must escape the backslashes there as well:
String s = "C:\\Program\\files\\images\\flower.jpg";
String[] tokens=s.split("\\\\");
Try this:
String s = "C:/Program/files/images/flower.jpg";
String[] tokens = s.split("/");
enter code hereString image= tokens[4];
Your original input text should be
C:\\Program\\files\\images\\flower.jpg
instead of
C:\Program\files\images\flower.jpg
This works,
public static void main(String[] args) {
String str = "C:\\Program\\files\\images\\flower.jpg";
str = str.replace("\\".toCharArray()[0], "/".toCharArray()[0]);
System.out.println(str);
String[] tokens = str.split("/");
System.out.println(tokens[4]);
}

Why String.replaceAll() don't work on this String?

//This source is a line read from a file
String src = "23570006,music,**,wu(),1,exam,\"Monday9,10(H2-301)\",1-10,score,";
//This sohuld be from a matcher.group() when Pattern.compile("\".*?\"")
String group = "\"Monday9,10(H2-301)\"";
src = src.replaceAll("\"", "");
group = group.replaceAll("\"", "");
String replacement = group.replaceAll(",", "##");
System.out.println(src.contains(group));
src = src.replaceAll(group, replacement);
System.out.println(group);
System.out.println(replacement);
System.out.println(src);
I'm trying to replace the "," between \"s so I can use String.split() latter.
But the above just not working , the result is:
true
Monday9,10(H2-301)
Monday9##10(H2-301)
23570006,music,**,wu(),1,exam,Monday9,10(H2-301),1-10,score,
but when I change the src string to
String src = "123\"9,10\"123";
String group = "\"9,10\"";
It works well
true
9,10
9##10
1239##10123
What's the matter with the string???
( and ) are regex metacharacter; they need to be escaped if you want to match it literally.
String group = "\"Monday9,10\\(H2-301\\)\"";
^ ^
The reason why you need two slashes is that because \ in a string literal is itself an escape character, so "\\" is a string of length 1 containing a slash.

Categories

Resources