Progress Programmer
Progress Programmer

Reputation: 7394

regular expression question

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?

Upvotes: 4

Views: 7651

Answers (2)

Tim H
Tim H

Reputation: 685

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.

Upvotes: 6

jjnguy
jjnguy

Reputation: 138884

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.

Upvotes: 15

Related Questions