How would I replace all that is not stored in the variable guess in the current Pattern with a “-“? The guess will change with different method calls. I want to replace anything that is not the char guess(in this case => ‘e’) with a “-“.
String word = "ally";
char guess = 'e';
String currentPattern = word.replaceAll("[^guess]", "-");
Obviously, this does not work.
You almost have it. Use String concatenation:
This approach only works if you don’t have regex metacharacters within
guess, which need to be escaped within character classes. Otherwise aPatternSyntaxExceptionwill be thrown.This question shows that in your case, where you only add a
charto your character class, aPatternSyntaxExceptionwon’t happen even if you don’t escape anything.