Remove Square Brackets and replace with Curly Brackets - java

I am trying to replace all the square brackets with the curly brackets.
Example:
String string = "{\"test\":{\"id\":["4,5,6"}]},{\"Tech\":["Java,C++"]}}";
I want to remove square brackets([,]) and replace them with curly brackets({,}).
Like:
"{\"test\":{\"id\":{"4,5,6"}}},{\"Tech\":{"Java,C++"}}}";
I have tried:
string = string.replace("\\[", "\\{").replace("\\]", "\\}");
But didnt worked.Need some suggestions here.

You don't need \\[ and \\{ for that you don't get the correct result, instead you can use :
System.out.println(string.replace("[", "{").replace("]", "}"));
Note
Your are using an invalid String you have to use \ before "\"" like this :
String string = "{\"test\":{\"id\":[\"4,5,6\"}]},{\"Tech\":[\"Java,C++\"]}}";

you can either do this:
str.replace('[', '{').replace(']', '}');
or you can do this:
str.replaceAll("\\[", "{").replaceAll("\\]", "}");
Replace uses Characters, thus the ' ' whereas replaceAll uses Regex. This is why you should escape your bracket there.

Related

How to replace single quote within a string with two single quotes in java?

I have the below data in my text file.
1|"John"|3,5400
2|"Jim"|7,7300
3|"Smith,Robin",3,4300
4|"O'Brien",10,8200
and I want this output:
(1,'John',3,5400)
(2,'Jim',7,7300)
(3,'Smith,Robin',3,4300)
(4,'O''Brien',10,8200)
Basically I want to replace | character with commas and double quotes with single quote. I am able to achieve that with this piece of code:
String text2 = textAfterHeader.replaceAll("\\|", ",").replaceAll("\"", "'").replaceAll("[a-zA-Z]'[a-zA-Z]", "''");
output that I am getting:
1,'John',3,5400
2,'Jim',7,7300
3,'Smith,Robin',3,4300
4,'''rien',10,8200
But I have one more requirement where I need to put two single quotes whenever a single quote appears between a string, for example, O'Brien as O''Brien. But this part is not working.
As was suggested by #AndyTurner, you can simplify the problem by first replacing all ' with '' and then replace all " with '. The only thing missing after that are the parenthesis, which can be added in two steps:
Replace all blanks with ) ( (notice the blank between the parenthesis).
Add a leading ( and a trailing ) to the String.
All together, a solution could look like this:
final String output = "("
+ input
.replace("'", "''")
.replace("\"", "'")
.replace("|", ",")
.replace(" ", ") (")
+ ")";
Ideone demo
Try this regex:
\s*\'\s*
and a call to Replace with " will do the job.
A possible solution could be:
String lineSeparator = System.getProperty("line.separator");
String output = new StringBuilder("(").append(
input.replaceAll("\\|", ",")
.replaceAll("'", "''") // (*)
.replaceAll("\"", "'") // (**)
.replaceAll(lineSeparator, ")" + lineSeparator + "("))
.append(")").toString();
Note the replacement (*) must come before (**). Since you need to replace exact characters instead of variable regular expressions, you want better use replace instead of replaceAll.

Replacing " Character by another character in a string

How do I replace Double quotes a well as single quotes for instance:
I want where there is a " to be replaced by nothing at all. I have tried
String quoteid3 = quoteid2.replace('"','');
and it causes an error.
You're going to need to escape your quotes. Like so, might help:
String quoteid3 = quoteid2.replace('\"','\'');
To replace ", escape the double quotes with \".
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
//To replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
This should work:
String quoteid3 = quoteid2.replaceAll("\"", "");
There are two versions of String.replace, one that takes a pair of char values and the other that takes a pair of String values. If you want the replacement value to be empty then you need to use the string version, i.e. use double (rather than single) quotes.
String quoteid3 = quoteid2.replace("\"","");
In Java a single quoted literal is a char and so must be exactly one character - '' is not valid. Double quoted literals represent strings, so can be any number of characters from zero upwards.
For replacing " , escape the the double quote \", Similarly escape ' with \'
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
Or if you want to stick to using replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
If you want to replace " , escape the the double quote \", Similarly escape ' with \'
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
Or alternatively if you want to stick to using replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
If you want to replace " , escape the the double quote \", Similarly escape ' with \'
Use replaceAll() to provide a regex [\"\'] that recognizes all ' and " , and replace it with "" from a String to remove the values (replace them with nothing).
String quoteid3 = quoteid2.replaceAll("[\"\']", "");
Or alternatively if you want to stick to using replace() without regex:-
String quoteid3 =quoteid2.replace("\"","").replace("\'","");
An empty String is a wrapper on a char[] with no elements. You can have an empty char[]. But you cannot have an "empty" char. Like other primitives, a char has to have a value.
So if you want to replace all Double quotes a well as single quotes by nothing at all
you can try this :
String str1="Hossam Hassan \"Greeting you\" \' \' \'";
System.out.println(str1);
String str2=str1.replaceAll("\"", "");
str2=str2.replaceAll("\'", "");
System.out.println(str2);
The result should be:
Hossam Hassan "Greeting you" ' ' '
Hossam Hassan Greeting you

Remove curly brace in Java

I have a text file in which each line begins and ends with a curly brace:
{aaa,":"bbb,ID":"ccc,}
{zzz,":"sss,ID":"fff,}
{ggg,":"hhh,ID":"kkk,} ...
Between the characters there are no spaces. I'm trying to remove the curly braces and replace them with white space as follows:
String s = "{aaa,":"bbb,ID":"ccc,}";
String n = s.replaceAll("{", " ");
I've tried escaping the curly brace using:
String n = s.replaceAll("/{", " ");
String n = s.replaceAll("'{'", " ");
None of this works, as it comes up with an error. Does anyone know a solution?
you cannot define a String like this:
String s = "{aaa,":"bbb,ID":"ccc,}";
The error is here, you have to escape the double quotes inside the string, like this:
String s = "{aaa,\":\"bbb,ID\":\"ccc,}";
Now there will be no error if you call
s.replaceAll("\\{", " ");
If you have an IDE (that is a program like eclipse), you will notice that a string is colored different from the standard color black (for example the color of a method or a semicolon [;]). If the string is all of the same color (usually brown, sometimes blue) then you should be ok, if you notice some black color inside, you are doing something wrong. Usually the only thing that you would put after a double quote ["] is a plus [+] followed by something that has to be added to the string. For example:
String firstPiece = "This is a ";
// this is ok:
String all = s + "String";
//if you call:
System.out.println(all);
//the output will be: This is a String
// this is not ok:
String allWrong = s "String";
//Even if you are putting one after the other the two strings, this is forbidden and is a Syntax error.
String.replaceAll() takes a regex, and regex requires escaping of the '{' character. So, replace:
s.replaceAll("{", " ");
with:
s.replaceAll("\\{", " ");
Note the double-escapes - one for the Java string, and one for the regex.
However, you don't really need a regex here since you're just matching a single character. So you could use the replace method instead:
s.replace("{", " "); // Replace string occurrences
s.replace('{', ' '); // Replace character occurrences
Or, use the regex version to replace both braces in one fell swoop:
s.replaceAll("[{}]", " ");
No escaping is needed here since the braces are inside a character class ([]).
Just adding to the answer above:
If somebody is trying like below, this won't work:
if(values.contains("\\{")){
values = values.replaceAll("\\{", "");
}
if(values.contains("\\}")){
values = values.replaceAll("\\}", "");
}
Use below code if you are using contains():
if(values.contains("{")){
values = values.replaceAll("\\{", "");
}
if(values.contains("}")){
values = values.replaceAll("\\}", "");
}

Split string by array of characters

i want to split a string by array of characters,
so i have this code:
String target = "hello,any|body here?";
char[] delim = {'|',',',' '};
String regex = "(" + new String(delim).replaceAll("(.)", "\\\\$1|").replaceAll("\\|$", ")");
String[] result = target.split(regex);
everything works fine except when i want to add a character like 'Q' to delim[] array,
it throws exception :
java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence near index 11
(\ |\,|\||\Q)
so how can i fix that to work with non-special characters as well?
thanks in advance
how can i fix that to work with non-special characters as well
Put square brackets around your characters, instead of escaping them. Make sure that if ^ is included in your list of characters, you need to make sure it's not the first character, or escape it separately if it's the only character on the list.
Dashes also need special treatment - they need to go at the beginning or at the end of the regex.
String delimStr = String(delim);
String regex;
if (delimStr.equals("^") {
regex = "\\^"
} else if (delimStr.charAt(0) == '^') {
// This assumes that all characters are distinct.
// You may need a stricter check to make this work in general case.
regex = "[" + delimStr.charAt(1) + delimStr + "]";
} else {
regex = "[" + delimStr + "]";
}
Using Pattern.quote and putting it in square brackets seems to work:
String regex = "[" + Pattern.quote(new String(delim)) + "]";
Tested with possible problem characters.
Q is not a control character in a regex, so you do not have to put the \\ before it (it only serves to mark that you must interpret the following character as a literal, and not as a control character).
Example
`\\.` in a regex means "a dot"
`.` in a regex means "any character"
\\Q fails because Q is not special character in a regex, so it does not need to be quoted.
I would make delim a String array and add the quotes to these values that need it.
delim = {"\\|", ..... "Q"};

replace all + with -

I am trying to replace a + character into a hyphen I have in my string.
String str = "word+word";
str.replaceAll('+ ', '-');
I tried using replace but it throwing an exception.Is there any other method to do this.
Use
str = str.replaceAll("\\+", "-");
A few errors in your code :
replaceAll takes strings, not chars
the + char must be escaped as the first argument is a regular expression (and \ itself must be escaped in java string literals)
you must take the return of the function : as String is immutable the function doesn't change it but returns another string
Just use replace:
str = str.replace('+', '-');
This one doesn't work on regex but take characters as they are.
Also as you see you have to reassing value again to your str variable because String in Java are immutable. In this case method replace doesn't change current String (str) but create new one with replaced + to '-'.
`replaceAll´ is for regular expressions and strings are immutable. Use:
str = str.replace("+", "-");
instead...
The replaceAll function takes a regular expression as its first argument. It so happens that + is a special character in regular expression language. Try replacing + with \\+. This will escape the plus sign, thus making the code to treat it like a normal character.
Also, the replaceAll method yields a string, so that will not work. Try doing:
String str = "word+word";
str = str.replaceAll("\\+ ", "-");
Use "" as opposed to '' in replaceAll.
String java.lang.String.replaceAll(String regex, String replacement)
If you are not sure about the escape sequence you need to use,
You could simply do this.
str = str.replaceAll(Pattern.quote("+"), "-");
This will automatically escape the regex predefined tokens to match in a literal way

Categories

Resources