How to escape \" as absolute, concrete, unique, single value? Java - java

I'm trying to replace \" backslash and quote to ", those characters are together in my text, so I do a replace but the compiler it say that my escaping syntax is incorrect:
String myText = "Animal:{\"name\":\"turkey\"}";
As you can observe here there is \" together so I'm want to replace by just one quote "
To look like this:
"Animal:{"name":"turkey"}"
So my replace its looks like:
myText.replaceAll("\\\"", "\"");
To escape a backslash we need \\
To escape a quote we need \"
With that logic I have this \\\" but its not working, its incorrect for the compiler...
I already tried:
myText.replaceAll("\\*", "");
But this one is not want I want in my string.
Any advice?

I think you are exposing the problem wrongly.
If you write a String like this in the source code:
String myText = "Animal:{\"name\":\"turkey\"}";
... the String is already escaped.
It means you may print :
System.out.println(myText);
... and you would get in output:
Animal:{"name":"turkey"}
... without need of doing anything else.
So I can only imagine two things:
Your question is: Can I write String myText = "Animal:{"name":"turkey"}"; without backslashes in the source code? => The answer is no, or the compiler wouldn't know what's the delimiter of the text and what's just another character of the text.
Your question is missing information: for example, you are receiving this String from a service which is responding in Json, and over the transport this String is keeping the backslashes on the quotes.
If that's the case, you should rather use the proper library to parse the message as JsonNode. Add a dependency to jackson-databind into your project and then use these methods:
ObjectMapper mapper = new ObjectMapper(); // <-- create ObjectMapper
JsonNode actualObj = mapper.readTree(jsonString); // <-- parse your Json string into a JsonNode
String niceJsonString = actualObj.toPrettyString(); // <-- formats the Json properly
If your question falls in my second guess, then I suggest you have a look at Jackson, it is a pretty powerful library to work with Json (a market standard for Json messaging in Java).

The problem is that the first argument of replaceAll is not just a String, it is a regex string, and regex also uses backslash to escape the next character. So you need another entire level of escaping, so that what you are passing to regex is the string you have, i.e. escape backslash escape quote, so that the regex will search for the sequence backslash quote.
myText.replaceAll("\\\\\\\"", "\"");
I think that's right.

Related

remove slash from jsonstring jackson lib java

I have large json string something like this:
[{\"name\":\"Nick\",\"role\":\"admin\",\"age\":\"32\",\"rating\":47}]
I want to remove every occurrence of \" with " in string.
for this i used String's `relaceAll("\\"","\"")
when i am print the string after replace its printing fine but when i am sending string to object in json. its appending slash , please guide me how to get rid of this slash
My expecting result:
[{"name":"Nick","role":"admin","age":"32","rating":47}]
For this i used String's relaceAll("\\"","\"") ...
The String#replaceAll() method interprets the argument as a RegEx (Regular Expression). The Backslash Character (\) is an escape character in both String & Regex.
Hence, you need to double-escape it for the RegEx to work.
Example:
myString = myString.replaceAll("\\\\", "\\\\\\\\");
You can also use String#replace() method to perfrom the same task like this:
myString = myString.replace("\\", "\\\\");

Java escaping hyphen "-" character using regex

I am using Java and have string which have value as shown below,
String data = "vale-cx";
data = data.replaceAll("\\-", "\\-\\");
I am replacing "-" inside of it and it is not working. Final value i am looking is "vale\-cx". Meaning, hyphen needs to be escaped.
Hyphen doesn't need to be escaped, but backslash needs to be escaped in the replacement expression, meaning you need an extra two backslashes before the hyphen (and none after):
data = data.replaceAll("-", "\\\\-");
Better yet, don't use regex at all:
data = data.replace("-", "\\-");
Try with \\\\- instead, e.g:
String data = "vale-cx";
System.out.println(data.replaceAll("\\-", "\\\\-"));
The hyphen is only special in regular expressions when used to create ranges in character classes, e.g. [A-Z]. You aren't doing that here, so you don't need any escaping at all.

How to store regex date pattern in JSON

My code requires me to store regex string in JSON. this is working fine for most of the patterns but lands in trouble when date pattern with '/' is used
i tried escaping with a '\'
(\\d{1,2}\/\\d{1,2}\/\\d{1,2}) this seems to be working fine as JSONLint does give any error
however the challenge is when i am trying to parse the JSON string in a JAVA program it gives error as it further requires '\' and '/' to be escaped. I have tried multiple options but not able to solve
I think your proposed regex escapes a backslash too many: Have a look at: https://regex101.com/r/xBFeZG/1
It's only the \ that needs to be escaped in java regexes, so transforming what I believe you want to that would be:
(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})
However, why not simply use a standard date format (like: dd/MM/yyyy -> see https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) and do something like:
LocalDate.parse(date, DateTimeFormatter.ofPattern(format)
If you have an expression like
\d{1,2}/\d{1,2}/\d{1,4}
then exporting it as JSON will produce something like this
{ "regex": "\\d{1,2}\/\\d{1,2}\/\\d{1,4}" }
with every "\" being escaped as "\\".
To parse correctly in Java, you really just have to "un-escape" the escaped backslashes, in other words, remove the leading backslash. Something like this should work:
String regex = jsonRegex.replaceAll("\\\\(.)", "$1");
EDIT: Forward slashes don't actually need to be escaped, although escaping them doesn't hurt. So, the expression will most probably be emitted in JSON like
\\d{1,2}/\\d{1,2}/\\d{1,4}

How to search for a special character in java string?

I am having some problem with searching for a special character "(".
I got a java.util.regex.PatternSyntaxException exception has occurred.
It might have something to do with "(" being treated as special character.
I am not very good with pattern expression. Can someone help me properly search for the escape character?
// I need to split the string at the "("
String myString = "Room Temperature (C)";
String splitList[] = myString.split ("("); // i got an exception
// I tried this but got compile error
String splitList[] = myString.split ("\(");
Try one of these:
string.split("\\(");
string.split(Pattern.quote("("));
Since a string split takes a regular expression as an argument, you need to escape characters properly. See Jon Skeet's answer on this here:
The reason you got an exception the first time is because split() takes a regular expression as argument, and ( has a special meaning there, as you suggest. To avoid this, you need to escape it using a \, like you tried.
What you missed, is that you also need to escape your backslashes with an extra \ in Java, meaning you need a total of two:
String splitList[] = myString.split ("\\(");
You need to escape the character via backslashes: string.split("\\(");
( is one of regex special characters. To escape it you can use e.g.
split(Pattern.quote("(")),
split("\\Q(\\E"),
split("\\("),
split("[(]").

regex to convert find instances a single \

I am looking to replace \n with \\n but so far my regex attempts are not working (Really it is any \ by itself, \n just happens to be the use case I have in the data).
What I need is something along the lines of:
any-non-\ followed by \ followed by any-non-\
Ultimately I'll be passing the regex to java.lang.String.replaceAll so a regex formatted for that would be great, but I can probably translate another style regex into what I need.
For example I after this program to print out "true"...
public class Main
{
public static void main(String[] args)
{
final String original;
final String altered;
final String expected;
original = "hello\nworld";
expected = "hello\\nworld";
altered = original.replaceAll("([^\\\\])\\\\([^\\\\])", "$1\\\\$2");
System.out.println(altered.equals(expected));
}
}
using this does work:
altered = original.replaceAll("\\n", "\\\\n");
The string should be
"[^\\\\]\\\\[^\\\\]"
You have to quadruple backslashes in a String constant that's meant for a regex; if you only doubled them, they would be escaped for the String but not for the regex.
So the actual code would be
myString = myString.replaceAll("([^\\\\])\\\\([^\\\\])", "$1\\\\$2");
Note that in the replacement, a quadruple backslash is now interpreted as two backslashes rather than one, since the regex engine is not parsing it. Edit: Actually, the regex engine does parse it since it has to check for the backreferences.
Edit: The above was assuming that there was a literal \n in the input string, which is represented in a string literal as "\\n". Since it apparently has a newline instead (represented as "\n"), the correct substitution would be
myString = myString.replaceAll("\\n", "\\\\n");
This must be repeated for any other special characters (\t, \r, \0, \\, etc.). As above, the replacement string looks exactly like the regex string but isn't.
So whenever there is 1 backslash, you want 2, but if there is 2, 3 or 4... in a row, leave them alone?
you want to replace
(?<=[^\\])\\(?!\\+)([^\\])
with
\\$1
That changes the string
hello\nworld and hello\\nworld and hello\\\nworld
into
hello\\nworld and hello\\nworld and hello\\\nworld
I don't know exactly what you need it for, but you could have a look at StringEscapeUtils from Commons Lang. They have plenty of methods doing things like that, and if you don't find exactly what you're searching for, you could have a look at the source to find inspiration :)
Whats wrong with using altered = original.replaceAll("\\n", "\\\\n"); ? That's exactly what i would have done.

Categories