java - 如何替换字符串中除某些字符之外的所有字符?
问题描述
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);
}
}
推荐阅读
- python - 使用 python 从 Salesforce 导入数据
- android - 如何获取前两个选择器意图并仅在android中为用户显示它们
- android - 使用 adb 进行深度链接,而不是在浏览器中
- angular - RxJs 间隔中的新请求
- python - Django:获取从一个视图启动的子进程(运行/完成)的状态并将其显示到另一个视图
- postgresql - 无法通过 Apache Tomcat 连接到 Postgres DB?
- binary-decision-diagram - 在 CUDD 中传递布尔表达式时出错(在 BuDDy 中工作)
- amazon-web-services - 将来自应用程序的日志存储在 Kubernetes 中
- git - git log --graph 表格格式
- mysql - 无法连接到 XAMPP 上的 FTP 服务器 (Mac)