String s1=s.replace('"', '\"');
here i want to replace " with \"
Try String s1 = s.replace("\"", "\\\"");
Explanation:
When referencing a quote or backslash in a string, i.e. anything inside double quotes, a \ is required to state that you want the quote to appear within the quotes, not end the quotes. Does this make sense?
For example, you would write String message = "She said \"Hello\" the other day.", so that the backslashes represent that the quotes don't actually end the whole string, but are rather to be part of the string.
String s1=s.replace("\"", "\\\"");
It will replace all " by \".
Related
I have a problem with one line of code, which goes like this:
string = string.replaceAll("sin()", "");
As you can see, in a string, all "sin()" need to be replaced with "". But the problem is that () is not treated as string and so this line of code replaces "sin()" with "()". Moreover, Android studio reports warning on the () saying empty group. I tried solving this with escape character, but that doesn't work. Would following code work by any chance?
String compare = "sin()";
string = string.replaceAll(compare, "");
replaceAll's first parameter is a regular expression, of which ( and ) are special characters. You would instead need to use
string = string.replaceAll("sin\\(\\)", "");
Note the use of \\ - \ is actually a special character in Java strings, so you must first escape the \ by using \\.
String z = "sin() is equal sin()";
Log.d("TEST",z);
z = z.replaceAll("sin\\(\\)", "");
Log.d("TEST",z);
Gives following output:
sin() is equal sin()
is equal
You need to separate your ( and ) because its a special charaters
So you need to use "\\"
example:
string = string.replaceAll("sin\\(\\)", "");
I am trying to remove double quotes before square bracket like "[
and I am using following code to do it but it says illegal escape charecter.
str = str.replace("\[","[");
I want to remove only double quotes ie " which is only before square bracket ie [. Please guide me.
You can use:
str = str.replaceAll("\"\\[", "[");
Both replace() and replaceAll() do the job. Using replace, you don't have to cope with regular expressions. Don't get confused by the name. In fact replace replaces all occurrences, not just the first.
str = str.replace("\"[", "[");
I have a string variable in my android ap which contains some url http://www.google.com. The string variable is declared as shown below:
String html="";
But there is an error saying that I have to put (semicolon); after the a href=". But actually I want the entire line content ie
(href="http://www.google.com") in the string variable. How can it be achieved?? Thanks in advance.
doubles quotes needs to escaped.
try below one
String html="<a href='http://www.google.com'></a>";
else
String html= "";
You need to escape every " with \ if you want to put it in one String.
For example:
String html="";
If you don't do this, compiler assumes, that you end this String after href= and tries to understand what http://www.google.com means in Java ;)
Im trying to use a question mark as a variable for a string.
I've tried...
strings.xml
<string name="questionMark">\?</string>
.class
String questionMark;
questionMark = getResources().getString(R.string.questionMark);
String delim4 = (questionMark);
This causes a fource close regex error.
and
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
and also
I've tried putting 2 backslashes in front of it
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well.
the output for that was
delim \?
Can any tell me how to put in the question mark as the string. I'm using it as variable to spit a string. The String Im splitting can not be changed.
plz help
Edit added split code
if (FinishedUrl.contains(questionMark)){
String delim3 = (".com/");
String[] parts3 = FinishedUrl.split(delim3);
String JUNK3= parts3[0];
String fIdStpOne = parts3[1];
String fIdStpTwo = fIdStpOne.replaceAll("=#!/","");
String delim4 = (questionMark);
String[] parts4 = fIdStpTwo.split(delim4);
String fIdStpThree= parts3[0];
String JUNK4 = parts3[1];
FId = fIdStpThree;
}
As pointed out by user laalto, ? is a meta-character in regex. You must work around that.
Let's see what's happening here. Firstly, some ground rules:
`?` is not a special character in Java
`?` is a reserved character in regex
This entails:
String test = "?"; // Valid statement in java, but illegal when used as a regex
String test = "\?"; // Illegal use of escape character
Why is the second statement wrong? Because we are trying to escape a character that isn't special (in Java). Okay, we'll get back to this.
Now, for the split(String) method, we need to escape the ? - it being a meta-character in regex. So, we need \? for the regex.
Coming back to the string, how do we get \?? We need to escape the \(backslash) - not the question mark!
Here's the workflow:
String delim4 = "\\?";
This statement gives us \? - it escapes the \(backslash).
String[] parts4 = fIdStpTwo.split(delim4);
This lets us use \? as a regex in the split() method. Since delim4 is being passed as a regex, \? is used as ?. Here, the prefix \ is used to escape ?.
Your observations:
String delim4 = (\?);
This gets an error Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \ )
I covered this above. You are escaping ? at the java level - but it isn't a special character and needs no escaping - hence the error.
String delim4 =(\\?)
System.out.println("delim "+ delim4);
But that just escapes the second slash and sometimes force closes as well. the output for that was
delim \?
This is what we want. It is easier to think of this as a two stage process. The first stage deals with successfully placing a \(backslash) in front of the ?. In the second stage, regex finds that the ? has been prefixed by a \ and uses ? as a literal instead of a meta-character.
And here's how you can place the regex in your res/values/strings.xml:
<string name="questionMark">\\?</string>
By the way, there's another option - not something I use on a regular basis these days - split() works just fine.
You can use StringTokenizer which works with delimiters instead of regex. Afaik, any literal can be used as a delimiter. So, you can use ? directly:
StringTokenizer st = new StringTokenizer(stringToSplit, "?");
while (st.hasMoreTokens()) {
// Use tokens
String token = st.nextToken();
}
Easiest way is to quote or backslash them:
<string name="random">"?"</string>
<string name="random">\?</string>
The final code.
String startDelim = ("\\?");
String realDelim = (startDelim);
String[] parts4 = fIdStpOne.split(realDelim);
String fIdStpTwo= parts4[0];
String JUNK4 = parts4[1];
Normally you'd just put it literally, like
String q = "?";
However, you say you're using it to split a string. split() takes a regular expression and ? is a metacharacter in a regex. To escape it, add a backslash in front. Backslash is a special character in Java string literals so it needs to be escaped, too:
String q = "\\?";
I am working with a project where some data are retrieved by JSON parsing. Unfortunately, invalid character '\' escapes. I need to remove them. I tried calling .replace("\\'","\");. This solution is not working. No exceptions are thrown, but the string does not change. Here is my code:
shop_name = c.getString(TAG_SHOP_NAME);
if(shop_name.contains("\\'")==true)
{
//try{
shop_name=shop_name.replaceAll(Pattern.quote("\\'"), "'");
Log.e("vvvvvv","new shop name: "+shop_name);}
//catch(Exception q){Log.e(TAG+" vvvv","EXPTN",q);}
}
send JSON object is: Bimal\'s
required object: Bimal's
Please let me know whether I went wrong somewhere or if there is any other method other than replaceAll.
You need to double escape the backslash as it's an escape character in both strings and regex:
shop_name.replaceAll("\\\\'", "'");
Or without using regex (as it's not needed in this circumstance):
shop_name.replace("\\'", "'");
Escape the meta character " with "\" :
string.replaceAll("\"", "");
Remember to assign it back to the String reference , because it returns a new String object.
You should use replace() instead:
str = str.replace("\"", "");
replaceAll() is used for replacing regular expressions.