Lukas
Lukas

Reputation: 76

Is There A Way To Use Regex Containing Variables To Replace Characters In A String

I already have the code s.replaceFirst("\\.", "");. This replaces the dot in the given string s. But my problem is, that it shall be able to change, what is going to be replaced. Like for example, the programm has to replace now a question mark. I tried to do it as following:

String characterToReplace = "?";
s = s.replaceFirst("\\" + characterToReplace, "");

But that just creates errors.

Upvotes: 0

Views: 43

Answers (1)

djhaskin987
djhaskin987

Reputation: 10087

Try using Pattern.quote, discussed here:

import java.util.regex.Pattern;

// ...

String characterToReplace = "?";
s = s.replaceFirst(Pattern.quote(characterToReplace), "");

Upvotes: 3

Related Questions