簡體   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);
    }
}
  • 電流輸出: 1c1g1
  • 想要的輸出: 11c111g111111111111111111

現在在這里我得到的輸出為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);
    }
}

即時復制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM