如何替换字符串中除某些字符以外的所有字符?

时间:2018-11-27 14:23:54

标签: java regex string

public class HelloWorld {
    public static void main(String []args) {
        //replace all char to 1 other then c and g
        String str = "abcdefghijklmnopqrstuvwxyz";
        if (str == null || str.length() == 0) {
            return;
        }
        String answer = str.replaceAll("[^cg]+", "1");
        System.out.println(answer);
    }
}
  • 当前输出:1c1g1
  • 想要的输出:11c111g111111111111111111

1 个答案:

答案 0 :(得分:2)

  

现在在这里我得到的输出为1c1g1,但我想要的是11c111g111111111111111111

删除+。也就是说“匹配上一个或多个”,但是您要用一个 1替换该系列的匹配字符。

所以:

public class HelloWorld {

    public static void main(String []args){
        //replace all char to 1 other then c and g
        String str = "abcdefghijklmnopqrstuvwxyz";
        if (str == null || str.length() == 0) {
            return;
        }
        String answer = str.replaceAll("[^cg]", "1");
        // No + here ------------------------^
        System.out.println(answer);
    }
}

Live Copy

相关问题