[英]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.