Why does the following not work:
String test = "hello\"world".replaceAll("\"", "\\\"");
System.out.println(test);
What I'm trying to do is replace any occurrence of " with \".
So I want to get as output:
hello\"world
Regular expressions are overkill for this.
myString.replace("\"", "\\\"")
should do just fine and is more readable to someone familiar with the core libraries.
The replace method just replaces one substring with another.
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
You need to two more \\ to escape the escape character, for a total of 5 \s.
\\ - escape the escape character
\\ - to display the character
\ - to escape the quote.
Try:
String test = "hello\"world".replaceAll("\"", "\\\\\"");
String test = "hello\"world".replaceAll("\"", "\\\\\"");
System.out.println(test);
Related
How to write a regular expression to match this \" (a backslash then a quote)? Assume I have a string like this:
click to search
I need to replace all the \" with a ", so the result would look like:
click to search
This one does not work: str.replaceAll("\\\"", "\"") because it only matches the quote. Not sure how to get around with the backslash. I could have removed the backslash first, but there are other backslashes in my string.
If you don't need any of regex mechanisms like predefined character classes \d, quantifiers etc. instead of replaceAll which expects regex use replace which expects literals
str = str.replace("\\\"","\"");
Both methods will replace all occurrences of targets, but replace will treat targets literally.
BUT if you really must use regex you are looking for
str = str.replaceAll("\\\\\"", "\"")
\ is special character in regex (used for instance to create \d - character class representing digits). To make regex treat \ as normal character you need to place another \ before it to turn off its special meaning (you need to escape it). So regex which we are trying to create is \\.
But to create string literal representing text \\ so you could pass it to regex engine you need to write it as four \ ("\\\\"), because \ is also special character in String literals (part of code written using "...") since it can be used for instance as \t to represent tabulator.
That is why you also need to escape \ there.
In short you need to escape \ twice:
in regex \\
and then in String literal "\\\\"
You don't need a regular expression.
str.replace("\\\"", "\"")
should work just fine.
The replace method takes two substrings and replaces all non-overlapping occurrences of the first with the second. Per the javadoc:
public String replace(CharSequence target,
CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
try this: str.replaceAll("\\\\\"", "\\\"")
because Java will replace \ twice:
(1) \\\\\" --> \\" (for string)
(2) \\" --> \" (for regex)
I am a beginner in Java. I don't understand how the below code is able to print all the characters in a string:-
System.out.println(yourString.replaceAll(".", "$0\n"));
I have tried reading the documentation on replaceAll and regex, still no clue.
"." is a regular expression which matches any single character. $0 in the replacement string is a placeholder for the full match of the regex. \n is a line break.
Summarized, this snippet replaces each character with itself and adds a line break after the character.
The syntax for replaceAll() method is as follows:
replaceAll(String regex, Stringreplacement) where:
regex : regular expression
replacement : replacement sequence of characters
so when you what to replace a character with \n basically every character will be printed in a different line. For example: yourString = "Hello." =>
output: Hello with every character on a different line
If the String (as you specified) is String yourString = "-"; so the result of System.out.println(yourString.replaceAll(".", "$0\n")); will be "-\n".
Actually, if you need to print all of the String characters why are you using replaceAll? Coz System.out.println(yourString); will do it perfectly.
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
For a string str_in = "instance (\\w+\\s+){0,8}deleted"; how can I extract instance and deleted by using the replaceAll function?
I tried str_in = str_in.replaceAll("(\\w+\\s+){0,8}", ""); but it didn't work.
If you, as your question states, really want to use replaceAll() instead of the (in my opinion more suitable) replace(), you can use the \Q and \E markers to match the string literally:
String str_in = "instance (\\w+\\s+){0,8}deleted";
System.out.println(str_in.replaceAll("\\Q(\\w+\\s+){0,8}\\E", ""));
prints
instance deleted
You will need to escape the single characters so that they lose their regex nature:
str_in.replaceAll("\\(\\\\w\\+\\\\s\\+\\)\\{0,8\\}", "")
Each escaping backslash needs to be escaped for itself because of the string literal.
Do you mean that (\\w+\\s+){0,8} is literally in the string, and you want to remove it? You will need to escape each \ again in your replaceAll, so that they are interpreted literally, not as part of a regex, and also the ( and {.
Use str_in.replace("(\\w+\\s+){0,8}", "");
replace()
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab"
replaceAll()
Replaces each substring of this string that matches the given regular expression with the given replacement
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 '\'