escaping backslash in java string literal [duplicate] - java

This question already has answers here:
Replacing single '\' with '\\' in Java
(6 answers)
Closed 7 years ago.
I am using Java for a while and come up with this problem:
I use hard-coded paths in windows like
"D:\Java-code\JavaProjects\workspace\eypros\src"
The problem is that I need to escape the backslash character in order to use it with string. So I manually escape each backslash:
"D:\\Java-code\\JavaProjects\\workspace\\eypros\\src"
Is there a way to automatically take the unescaped path and return an escaped java string.
I am thinking that maybe another container besides java string could do the trick (but I don't know any).
Any suggestions?

public static String escapePath(String path)
{
return path.replace("\\", "\\\\");
}
The \ is doubled since it must be escaped in those strings also.
Anyway, I think you should use System.getProperty("file.separator"); instead of \.
Also the java.io.File has a few methods useful for file-system paths.

Related

why can't System.out.println print "C:\Users\Public"? [duplicate]

This question already has answers here:
How can I make Java print quotes, like "Hello"?
(11 answers)
What is the backslash character (\\)?
(6 answers)
Closed 2 years ago.
basically i want the output to be Path = "C:\Users\Public" and it seems to me that System.out.println("Path = "C:\Users\Public""); should work, but it doesn't so the question is why can't java just print the phrase as a combination of characters?
btw. this is my second time "programing" so please in simple terms if possible.
You should escape the special character such as " and \
System.out.println("Path = \"C:\\Users\\Public\"");
When you use backslash (\), java assumes that you are going to use an escape character. If you want to print that line you should probably use the method below and it should work. And you are using a string inside another one so you should use different types of inverted commas for both to tell the compiler that yeah there is a string inside another one. Otherwise the compiler will assume the middle inverted comma to be the closing one.
You can escape each and every escape character. If you notice I have used a backslash before inner inverted commas (" ") and every other backslash (\). Using a backslash before any escape character escapes it. So this should work.
System.out.println("Path = \"C:\\Users\\Public\"");
I hope now you can print your required output.

Java doesn't split "|" symbol correctly [duplicate]

This question already has answers here:
Splitting a Java String by the pipe symbol using split("|")
(7 answers)
Closed 7 years ago.
I have a file with content
1|yes|
2|yes|
3|yes|
4|yes|
5|yes|
6|yes|
7|yes|
8|yes|
9|yes|
10|yes|
11|yes|
12|yes|
13|yes|
14|yes|
15|yes|
I use java's String[] tokens = split("|"); to split each line, but it returns (for example splitting "10|yes|") [1,0,|,y,e,s,|]. It seems instead of splitting by "|", it splits every character. Anyone has any idea on it? Thanks!
split accepts a regular expression. | has a specific meaning in regular expressions, it expresses an alternation. To actually split on |, you have to escape it in the regex with a backslash. Since you specify the regex using a string literal, and backslashes are special in string literals, you have to escape that with another backslash:
String[] tokens = str.split("\\|");
In the general case, if you want to use the contents of a string literally, you can use Pattern.quote to automatically escape any special characters. You don't really need it here, but it's useful for end-user-entered values:
String[] tokens = str.split(Pattern.quote(stringToSplitOnLiterally));

how to separate a java string that is separated by "$"? [duplicate]

This question already has answers here:
illegal string body character after dollar sign
(5 answers)
Closed 8 years ago.
I am using spock to test a java app.It seems "$" is a special character in groovy.any java string that is separated by "$" can't be separated in groovy properly.Any workaround for this problem?
update
The "split" happened in java code that I can't edit. It turns out that java code has a problem same as:Why can't I split a string with the dollar sign?
I don't think $ is a special character in Groovy strings. Edit: Yes, it is, if you use GStrings! But the rest may still be useful: But it's a special character in the string you give to String#split, because that string is interpreted as a regular expression, and in a regular expression, $ is "end of input" (or end of line, depending on flags).
If you're using String#split, to make it split on a literal $, you have to escape it with a backslash. To make the regex engine see a backslash, you have to escape the backslash in a string literal with another backslash.
Example:
'testing$one$two$three'.split('\\$').each {
println it
}
Output:
testing
one
two
three
Better yet, as suggested by Dónal, use tokenize:
Example:
'testing$one$two$three'.tokenize('$').each {
println it
}
(Same output)

Splitting on "," but not "\," [duplicate]

This question already has answers here:
How to split a comma separated String while ignoring escaped commas?
(6 answers)
Closed 9 years ago.
I'm looking for a regular expression to match , but ignore \, in Java's regex engine. This comes close:
[^\\],
However, it matches the previous character (in addition to the comma), which won't work.
Perhaps the regular expression approach is the wrong one altogether. I was intending to use String.split() to parse a simple CSV file (can't use an external library) with escaped commas.
You need a negative look-behind assertion here:
String[] arr = str.split("(?<![^\\\\]\\\\),");
Note that you need 4 backslashes there. First escape the backslash for Java string literal. And then again escape both the backslashes for regex.

Replace all with a string having regex wild chars [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java String.replaceAll without regex
I have a string and I need to replace some parts of it.
The replacement text contains regex wild chars though. Example:
String target = "Something * to do in ('AAA', 'BBB')";
String replacement = "Hello";
String originalText = "ABCDEFHGIJKLMN" + target + "ABCDEFHGIJKLMN";
System.out.println(originalText.replaceAll(target, replacement));
I get:
ABCDEFHGIJKLMNSomething * to do in ('AAA', 'BBB')ABCDEFHGIJKLMN
Why doesn't the replacement occur?
Because *, ( and ) are all meta-characters in regular expressions. Hence all of them need to be escaped. It looks like Java has a convenient method for this:
java.util.regex.Pattern.quote(target)
However, the better option might be, to just not use the regex-using replaceAll function but simply replace. Then you do not need to escape anything.
String.replaceAll() takes a regular expression and so it's trying to expand these metacharacters.
One approach is to escape these chars (e.g. \*).
Another would be to do the replacement yourself by using String.indexOf() and finding the start of the contained string. indexOf() doesn't take a regexp but rather a normal string.

Categories