I want to replace the question mark (?) in a string with some other words. What is the regular expression for question mark. For example, I want to replace question mark in "word=?" to something else, say "stackoverflow". Then the result would be "word=stackoverflow". What is the syntax in java?
+8
A:
string.replaceFirst("\\?", yourWord)
That will replace the first occurrence of a '?'
in your code with whatever yourWord
is.
If you want to replace every '?'
with yourWord
then use string.replaceAll("\\?", yourWord)
.
See the javadocs for more info.
jjnguy
2009-07-20 20:41:23
To avoid confusion about (Java) strings and immutability, I always try to phrase answers like this as assignment expressions: `str = str.replaceFirst("\\?", yourWord);`
Alan Moore
2009-07-21 02:00:31
+2
A:
As a general rule, you can take the "magic" out of magic characters such as "?
", "*
", ".
" and so forth, by using the escape character, which is a backslash ("\
").
The tricky part is that in Java, in a string, the backslash is ALREADY used as an escape, so to construct a Java String whose value is "\?
", you have to code it as "\\?
" so as to escape the escape character.
Tim H
2009-07-20 20:55:40