Regular Expression Question

I want to replace the question mark (?) In the string with other words. What is the regular expression for a question mark. For example, I want to replace the question mark with "word =?" on something else, say "stackoverflow". Then the result will be "word = stackoverflow". What is the syntax in java?

+4
source share
2 answers
string.replaceFirst("\\?", yourWord) 

This will replace the first occurrence of '?' in your code by any yourWord .

If you want to replace each '?' on yourWord , use string.replaceAll("\\?", yourWord) .

See javadocs for more details.

+15
source

Typically, you can take β€œmagic” from magic characters such as β€œ ? ”, β€œ * ”, β€œ . ”, Etc., using an escape character that is a backslash (β€œ \ ”).

The tricky part is that in Java, in a string, the backslash is ALREADY used as escape, so to construct a Java string whose value is " \? ", You must encode it as " \\? " To avoid the escape character .

+6
source

All Articles