简体   繁体   English

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

[英]How to replace all characters in a String except certain character?

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);
    }
}
  • Current output: 1c1g1 电流输出: 1c1g1
  • Wanted output: 11c111g111111111111111111 想要的输出: 11c111g111111111111111111

Now here I am getting an output as 1c1g1, but what I want is 11c111g111111111111111111 现在在这里我得到的输出为1c1g1,但是我想要的是11c111g111111111111111111

Remove the + . 删除+ That says "match one or more of the previous" but you're replacing that series of matching characters with one 1 . 这表示“匹配上一个或多个上一个”,但是您要用一个 1替换该系列的匹配字符。

So: 所以:

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 即时复制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM