如何使用模式中的变量替换所有除外?

时间:2013-02-21 07:52:53

标签: java regex string

如何使用" - "替换当前Pattern中未存储在变量guess中的所有内容?猜测将随着不同的方法调用而改变。我想用" - "替换任何不是char猜测的东西(在这种情况下=>')。

String word = "ally";
char guess = 'e';
String currentPattern = word.replaceAll("[^guess]", "-");

显然,这不起作用。

4 个答案:

答案 0 :(得分:4)

你几乎拥有它。使用字符串连接:

String currentPattern = word.replaceAll("[^" + guess + "]", "-");

此方法仅在guess内没有正则表达式元字符时才有效,需要在字符类中进行转义。否则将抛出PatternSyntaxException

这个question表明,在您的情况下,只向您的角色类添加char,即使您没有逃避任何事情,也不会发生PatternSyntaxException。< / p>

答案 1 :(得分:0)

你几乎就在那里,只需使用+连接运算符来连接正则表达式部分的猜测。

            String word = "ally";
        char guess = 'e';
        String currentPattern = word.replaceAll("[^"+guess+"]", "-");
        System.out.println(currentPattern);

答案 2 :(得分:0)

您需要在正则表达式字符串中明确包含变量:

String word = "alely";
char guess = 'e';
System.out.println(word.replaceAll(String.format("[^%s]", guess), "-"));

答案 3 :(得分:0)

把它变成一种方法?

public String replaceAllExcept( String input, char pattern ) {
    return input.replaceAll( "[^" + pattern + "]", "-" );
}

System.out.println( replaceAllExcept( "ally", 'e' );
System.out.println( replaceAllExcept( "tree", 'e' );