[英]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
1c1g1
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.