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
答案 0 :(得分:2)
现在在这里我得到的输出为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);
}
}