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
Related
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.
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"};
I want to replace \ with . in String java.
Example src\main\java\com\myapp\AppJobExecutionListener
Here I want to get like src.main.java.com.myapp.AppJobExecutionListener
I tried str.replaceAll("\\","[.]") and str.replaceAll("\\","[.]") but it is not working.
I am still getting original string src\main\java\com\myapp\AppJobExecutionListener
String is immutable in Java, so whatever methods you invoke on the String object are not reflected on it unless you reassign it.
String s = "ABC";
s.replaceAll("B","D");
System.out.println(s); //still prints "ABC"
s = s.replaceAll("B","D");
System.out.println(s); //prints "ADC"
Currently you're using replaceAll, which takes regular expression patterns. That makes life much more complicated than it needs to be. Unless you're trying to use regular expressions, just use String.replace instead.
In fact, as you're only replacing one character with another, you can just use character literals:
String replaced = original.replace('\\', '.');
The \ is doubled as it's the escape character in Java character literals - but as the above doesn't use regular expressions, the period has no special meaning.
Assign it back to string str variable, .String#replaceAll doesn't changes the string itself, it returns a new String.
str = str.replaceAll("\\\\",".")
Can you try this:
String original = "Some text with \\ and rest of the text";
String replaced = original.replace("\\",".");
System.out.println(replaced);
'\' character is doubled in a string like '\\'. So '\\' character should be used to replace it with '.' character and also using replace instead of replaceAll would be enough to make it. Here is a sample;
public static void main(String[] args) {
String myString = "src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
System.out.println("Before Replaced: " + myString);
myString = myString.replace("\\", ".");
System.out.println("After Replaced: " + myString);
}
This will give you:
Before Replaced: src\main\java\com\vxl\appanalytix\AppJobExecutionListener
After Replaced: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
With String replaceAll(String regex, String replacement):
str = str.replaceAll("\\\\", ".");
With String replace(char oldChar, char newChar):
str = str.replace('\\', '.');
With String replace(CharSequence target, CharSequence replacement)
str = str.replace("\\", ".");
String replaced = original.replace('\', '.');
try this its works well
Use replace instead of replaceall
String my_str="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
String my_new_str = my_str.replace("\\", ".");
System.out.println(my_new_str);
DEMO AT IDEONE.COM
replaceAll takes a regex as the first parameter.
To replace the \ you need to double escape. You need an additional \ to escape the first . And as it is a regex input you need to escape those again. As other answers have said string is immutable so you will need to assign the result
String newStr = str.replaceAll("\\\\", ".");
The second parameter is not regex so you can just put . in there but note you need four slashes to replace one backslash if using replaceAll
i tried this:
String s="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
s = s.replace("\\", ".");
System.out.println("s: "+ s);
output: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
Just change the line to
str = str.replaceAll("\\",".");
Edit : I didnt try it, because the problem here is not whether its a correct regex,but the problem here is that he is not assigning the str to new str value. Anyways regex corrected now.
I want to split a string "ABC\DEF" ?
I have tried
String str = "ABC\DEF";
String[] values1 = str.split("\\");
String[] values2 = str.split("\");
But none seems to be working. Please help.
String.split() expects a regular expression. You need to escape each \ because it is in a java string (by the way you should escape on String str = "ABC\DEF"; too), and you need to escape for the regex. In the end, you will end with this line:
String[] values = str.split("\\\\");
The "\\\\" will be the \\ string, which the regex will interpret as \.
Note that String.split splits a string by regex.
One correct way1 to specify \ as delimiter, in RAW regex is:
\\
Since \ is special character in regex, you need to escape it to specify the literal \.
Putting the regex in string literal, you need to escape again, since \ is also escape character in string literal. Therefore, you end up with:
"\\\\"
So your code should be:
str.split("\\\\")
Note that this splits on every single instance of \ in the string.
Footnote
1 Other ways (in RAW regex) are:
\x5C
\0134
\u005C
In string literal (even worse than the quadruple escaping):
"\\x5C"
"\\0134"
"\\u005C"
Use it:
String str = "ABC\\DEF";
String[] values1 = str.split("\\\\");
final String HAY = "_0_";
String str = "ABC\\DEF".replace("\\", HAY);
System.out.println(Arrays.asList(str.split(HAY)));
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