如何用“-”替换当前 Pattern
中变量 guess 中未存储的所有内容?猜测会随着不同的方法调用而改变。我想用“-”替换任何不是字符猜测(在本例中为 => 'e')的内容。
String word = "ally";
char guess = 'e';
String currentPattern = word.replaceAll("[^guess]", "-");
显然,这是行不通的。
最佳答案
你几乎拥有它。使用字符串连接:
String currentPattern = word.replaceAll("[^" + guess + "]", "-");
此方法仅适用于 guess
中没有正则表达式元字符的情况,需要在字符类中进行转义。否则将抛出 PatternSyntaxException
。
这question显示在您的情况下,您只将 char
添加到您的字符类,即使您不转义任何内容,也不会发生 PatternSyntaxException
。
关于java - 如何使用模式中的变量来替换所有除外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14997104/