首页 > 解决方案 > 如何替换字符串中除某些字符之外的所有字符?

问题描述

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);
    }
}

标签: javaregexstring

解决方案


现在在这里我得到一个输出为 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);
    }
}

实时复制


推荐阅读