String's replaceAll() method and escape characters - java

The line
System.out.println("\\");
prints a single back-slash (\). And
System.out.println("\\\\");
prints double back-slashes (\\). Understood!
But why in the following code:
class ReplaceTest
{
public static void main(String[] args)
{
String s = "hello.world";
s = s.replaceAll("\\.", "\\\\");
System.out.println(s);
}
}
is the output:
hello\world
instead of
hello\\world
After all, the replaceAll() method is replacing a dot (\\.) with (\\\\).
Can someone please explain this?

When replacing characters using regular expressions, you're allowed to use backreferences, such as \1 to replace a using a grouping within the match.
This, however, means that the backslash is a special character, so if you actually want to use a backslash it needs to be escaped.
Which means it needs to actually be escaped twice when using it in a Java string. (First for the string parser, then for the regex parser.)

The javadoc of replaceAll says:
Note that backslashes ( \ ) and dollar signs ($) in the replacement
string may cause the results to be different than if it were being
treated as a literal replacement string; see Matcher.replaceAll. Use
Matcher.quoteReplacement(java.lang.String) to suppress the special
meaning of these characters, if desired.

This is a formatted addendum to my comment
s = s.replaceAll("\\.", Matcher.quoteReplacement("\\"));
IS MORE READABLE AND MEANINGFUL THAN
s = s.replaceAll("\\.", "\\\\\\");

If you don't need regex for replacing and just need to replace exact strings, escape regex control characters before replace
String trickyString = "$Ha!I'm tricky|.|";
String safeToUseInReplaceAllString = Pattern.quote(trickyString);

The backslash is an escape character in Java Strings. e.g. backslash has a predefined meaning in Java. You have to use "\ \" to define a single backslash. If you want to define " \ w" then you must be using "\ \ w" in your regex. If you want to use backslash you as a literal you have to type \ \ \ \ as \ is also a escape character in regular expressions.

I believe in this particular case it would be easier to use replace instead of replace all.
Reverend Gonzo Has the correct answer when he talks about escaping the character.
Using replaceAll:
s = s.replaceAll("\\.", "\\\\\\\\");
Using replace:
s = s.replaceAll(".", "\\");
replace just takes a string to match to, not a regular expression.

I don't like this implementation of regex. We should be able to escape characters with a single '\' , not '\'. But anyway if you want to get THIS.Out_Of_That you can do:
String prefix = role.replaceFirst("(\\.).*", "");
So you get prefix = THIS;

Related

Java - escaping double quotes in string from file

I have html string from file. I need to escape all double quotes. So I do this way:
String content=readFile(file.getAbsolutePath(), StandardCharsets.UTF_8);
content=content.replaceAll("\"","\\\"");
System.out.println(content);
However, the double quotes are not escaped and the string is the same as it was before replaceAll method. When I do
String content=readFile(file.getAbsolutePath(), StandardCharsets.UTF_8);
content=content.replaceAll("\"","^^^");
System.out.println(content);
All double quotes are replaced with ^^^.
Why content.replaceAll("\"","\\\""); doesn't work?
You need to use 4 backslashes to denote one literal backslash in the replacement pattern:
content=content.replaceAll("\"","\\\\\"");
Here, \\\\ means a literal \ and \" means a literal ".
More details at Java String#replaceAll documentation:
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll
And later in Matcher.replaceAll documentation:
Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
Another fun replacement is replacing quotes with dollar sign: the replacement is "\\$". The 2 \s turn into 1 literal \ for the regex engine and it escapes the special character $ used to define backreferences. So, now it is a literal inside the replacement pattern.
You need to do :
String content = "some content with \" quotes.";
content = content.replaceAll("\"", "\\\\\"");
Why will this work?
\" represents the " symbol, while you need \".
If you add a \ as a prefix (\\") then you'll have to escape the prefix too, i.e. you'll have a \\\". This will now represent \", where \ is not the escaping character, but the symbol \.
However in the Java String the " character will be escaped with a \ and you will have to replace it as well. Therefore prefixing again with \\ will do fine:
x = x.replaceAll("\"", "\\\\\"");
It took me way too long in Java to discover Pattern.quote and Matcher.quoteReplacement. These will you achieve what you are trying to do here - which is a simple "find" and "replace" - without any regex and escape logic. The Pattern.quote here would not be necessary but it shows how you can ensure that the "find" part is not interpreted as a regex string:
#Test
public void testEscapeQuotes()
{
String content="some content with \"quotes\".";
content=content.replaceAll(Pattern.quote("\""), Matcher.quoteReplacement("\\\""));
Assert.assertEquals("some content with \\\"quotes\\\".", content);
}
Remember that you can also use the simple .replace method which will also "replaceAll" but will not interpret your parameters as regular expressions:
#Test
public void testEscapeQuotes()
{
String content="some content with \"quotes\".";
content=content.replace("\"", "\\\"");
Assert.assertEquals("some content with \\\"quotes\\\".", content);
}
Much easier with Apache Commons Text-
System.out.println(StringEscapeUtils.escapeJava("\""));
Output:
\"
Honestly, I am surprised by the behaviour, but it seems like you need to double-escape the backslash:
System.out.println("\"Hello world\"".replaceAll("\"", "\\\\\""));
which outputs:
\"Hello world\"
Demo

How Java replaceAll operation works with backslashes?

Why do I need four backslashes (\) to add one backslash into a String?
String replacedValue = neName.replaceAll(",", "\\\\,");
Here in above code you can check I have to replace all commas (,) from \, but I have to add three more backslash (\) ?
Can anybody explain this concept?
Escape once for Java, and a second time for regexp.
\ -> \\ -> \\\\
Or since you're not actually using regular expressions, take khelwood's advice and use replace(String,String) so you need to only escape once.
The documentation of String.replaceAll(regex, replacement) states:
Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll.
The documentation of Matcher.replaceAll(replacement) then states:
backslashes are used to escape literal characters in the replacement string
So to put this more clearly, when you replace with \,, it is as if you were escaping the comma. But what you want is really the \ character, so you should escape it with \\,. Since that in Java, \ also needs to be escaped, the replacement String becomes \\\\,.
If you are having a hard time remembering all this, you can use the method Matcher.quoteReplacement(s), whose goal is to correctly escape the replacement part. Your code would become:
String replacedValue = neName.replaceAll(",", Matcher.quoteReplacement("\\,"));
\ is used for escape sequence
For example
go to next line then use \n or \r
for tab \t
likewise to print \ which is special in string literal you have to escape it with another \ which gives us \\
Now replaceAll should be used with a regex, since you're not using a regex, use replace as suggested in the comments.
String s = neName.replace(",", "\\,");
You have to first escape the backslash because it's a literal (giving \\), and then escape it again because of the regular expression (giving \\\\).
Therefore this -
String replacedValue = neName.replaceAll(",", "\\\\,"); // you need ////
You can use replace instead of replaceAll-
String replacedValue = neName.replace(",", "\\,");

How to split a string with double quotes " as the delimiter?

I tried splitting like this-
tableData.split("\\"")
but it does not work.
It seems that you tried to escape it same way as you would escape | which is "\\|". But difference between | and " is that
| is metacharacter in regex engine (it represents OR operator)
" is metacharacter in Java language in string literal (it represents start/end of the string)
To escape any String metacharacter (like ") you need to place before it other String metacharacter responsible for escaping which is \1. So to create String which would contain " like this is "quote" you would need to write it as
String s = "this is \"quote\"";
// ^^ ^^ these represent " literal, not end of string
Same idea is applied if we would like to create \ literal (we would need to escape it by placing another \ before it). For instance if we would want to create string representing c:\foo\bar we would need to write it as
String s = "c:\\foo\\bar";
// ^^ ^^ these will represent \ literal
So as you see \ is used to escape metacharacters (make them simple literals).
This character is used in Java language for Strings, but it also is used in regex engine to escape its metacharacters:
\, ^, $, ., |, ?, *, +, (, ), [, {.
If you would like to create regex which will match [ character you will need to use regex \[ but String representing this regex in Java needs to be written as
String leftBracketRegex = "\\[";
// ^^ - Remember what was said earlier?
// To create \ literal in String we need to escape it
So to split on [ we would need to invoke split("\\[") because regex representing [ is \[ which needs to be written as "\\[" in Java.
Since " is not special character in regex but it is special in String we need to escape it only in string literal by writing it as
split("\"");
1) \ is also used to create other characters line separators \n, tab \t. It can also be used to create Unicode characters like \uXXXX where XXXX is index of character in Unicode table in hexadecimal form.
You have escaped the \ by putting in \ twice, try
tableData.split("\"")
Why does this happen?
A backslash escapes the following character. Since the next character is another backslash, the second backslash will be escaped, thus the doublequote won't.
Your resulting escaped string is \", where it should really be just ".
Edit:
Also keep in mind, that String.split() interprets its pattern parameter as a regular expression, which has several special characters, which have to be escaped in the resulting string.
So if you want split by a .(which is a special regex character), you need to specify it as String.split("\\."). The first backslash escapes the escaping function of the second backlash and would result in "\.".
In case of regex characters you could also just use Pattern.quote(); to escape your desired delimiter, but this is far out of the scope the question orignally had.
Try with single backslash \
tableData.split("\"")
Try like this by escaping " with single backslash \ :
tableData.split("\"")
You are not escaping properly. The snippet code will not even compile because of it. The correct way to do it is
tableData.split("\"");
A single backslash will do the trick.
Like this:
tableData.split("\"");
You can actually split without the backward slash. You only have to use single quote
tableData.split('"');

Why does .split("\\") generate an exception?

I have a String representing a directory, where \ is used to separate folders. I want to split based on "\\":
String address = "C:\\saeed\\test";
String[] splited = address.split("\\");
However, this is giving me a java.util.regex.PatternSyntaxException.
As others have suggested, you could use:
String[] separated = address.split("\\\\");
or you could use:
String[] separated = address.split(Pattern.quote("\\"));
Also, for reference:
String address = "C:\saeed\test";
will not compile, since \s is not a valid escape sequence. Here \t is interpreted as the tab character, what you actually want is:
String address = "C:\\saeed\\test";
So, now we see that in order to get a \ in a String, we need "\\". The regular expression \\ matches a single backslash since \ is a special character in regex, and hence must be escaped. Once we put this in quotes, aka turn it into a String, we need to escape each of the backslashes, yielding "\\\\".
String#split() method takes a regex. In regex, you need to escape the backslashes. And then for string literals in Java, you need to escape the backslash. In all, you need to use 4 backslashes:
String[] splited = address.split("\\\\");
\ has meaning as a part of the regex, so it too must be quoted. Try \\\\.
The Java will have at \\\\, and produce \\ which is what the regex processor needs to obtain \.
You need to use \\\\ instead of \\.
The backslash(\) is an escape character in Java Strings.If you want to use backslash as a literal you have to type \\\\ ,as \ is also a escape character in regular expressions.
For more details click here
Use separators:
String address = "C:\saeed\test";
String[] splited = address.split(System.getProperty("file.separator"));

String format using java

I have to make below statement as string.i am trying,but it's giving invalid character sequence.I know it is basic,But not able to do this.any help on this appreciated.
String str="_1";
'\str%' ESCAPE '\'
Output should be: '\_1%' ESCAPE '\'.
Thanks,
Chaitu
String result = "'\\" + str + "%' ESCAPE '\\'";
Inside a string, a backslash character will "escape" the character after it - which causes that character to be treated differently.
Since \ has this special meaning, if you actually want the \ character itself in the string, you need to put \\. The first backslash escapes the second, causing it to be treated as a literal \ inside the string.
Knowing this, you should be able to construct the resulting string you need. Hope this helps.
String str="_1";
String source = "'\\str%' ESCAPE '\\'";
String result = source.replaceAll("str", str);
Another way to implement string interpolation. The replaceAll function finds all occurrences of str in the source string and replaces them by the passed argument.
To encode the backslash \ in a Java string, you have to duplicate it, because a single backslash works as an escape character.
Beware that the first argument if replaceAll is actually a regular expression, so some characters have a special meaning, but for simple words it will work as expected.
String str="_1";
String output = String.format("'\\%s%%' ESCAPE '\\'",str);
System.out.println(output);//prints '\_1%' ESCAPE '\'

Categories

Resources