简体   繁体   中英

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
  • Wanted output: 11c111g111111111111111111

Now here I am getting an output as 1c1g1, but what I want is 11c111g111111111111111111

Remove the + . That says "match one or more of the previous" but you're replacing that series of matching characters with one 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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