Java 实现repalceAll只替换第二个匹配到的字符串
作者:蜗牛写java 时间:2021-06-12 11:56:20
String replace replaceFirst repaceAll区别
replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
replaceAll(String regex, String replacement)
使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串
replaceFirst(String regex, String replacement)
使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。
总结:
replace 替换的是char,replaceAll、replaceFirst替换的可以是字符串,也可以是正则表达式;三者返回的都是一个新的字符串。
例题
需求:将字符串 time:[* TO *] 中第二个*替换为 test
实现代码
@Test
public void replaceSecondStr() {
String test = "time:[* TO *]";
String result1 = test.replaceAll("(\\*)(.*?)(\\1)(.*?)", "$1$2test$4");
System.out.println("原字符串:" + test);
System.out.println("替换后:" + result1);
}
输出:
原字符串:time:[* TO *]
替换后:time:[* TO test]
总结:
正则中()表示提取匹配的字符串并分组;会分配存储空间,可以用$1取得匹配到的字符串;
\\1表示与第一个()中匹配的内容相同,也可以继续写(\\*);
(.*?)为勉强匹配方式,意思是匹配任何字符。
补充(取出匹配到的字符串)
@Test
public void findGroup() {
String test = "time:[* TO *]";
Matcher matcher = Pattern.compile("(\\*)(.*?)(\\1)(.*?)").matcher(test);
if (matcher.find()) {
System.out.println(matcher.group());
}
}
补充知识:java字符串的操作:去除字符、替换字符、多个字符分隔字符串
看代码吧~
// 去除空格,换行,制表符
public String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n"); // 去除多个空格,去除制表符,回车,换行
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
String s = "你要去除的字符串";
1.去除空格:s = s.replace('\\s','');
2.去除回车:s = s.replace('\n','');
字符串去除多个字符串(括号):
String cal = tableStrings.get(i).replaceAll("\\(|\\)", ""); // 去除左右括号
字符串分隔多个字符:
String[] temp = cal.split("\\+|\\-|\\*|\\/"); // 按照加减乘除字符分隔字符串
来源:https://blog.csdn.net/dwb502/article/details/77727194
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于WebClient实现Http协议的Post与Get对网站进行模拟登陆和浏览实例
spring mvc实现登录账号单浏览器登录
JAVASE系统实现抽卡功能
![](https://img.aspxhome.com/file/2023/0/58700_0s.jpg)
Mybatis基于xml配置实现单表的增删改查功能
实例讲述Java IO文件复制
详解Spring Boot集成MyBatis(注解方式)
![](https://img.aspxhome.com/file/2023/1/64481_0s.jpg)
关于java 图形验证码的解决方法
Java选择排序和垃圾回收机制详情
Java京东面试题之为什么HashMap线程不安全
![](https://img.aspxhome.com/file/2023/5/65615_0s.png)
java生成图片验证码实例代码
SpringBoot在Controller层接收参数的n种姿势(超详细)
![](https://img.aspxhome.com/file/2023/0/60600_0s.jpg)
dubbo如何实现consumer从多个group中调用指定group的provider
![](https://img.aspxhome.com/file/2023/0/68220_0s.png)
使用反射方式获取JPA Entity的属性和值
java写的伪微信红包功能示例代码
Swagger实现动态条件注入与全局拦截功能详细流程
轻松学习C#的方法
![](https://img.aspxhome.com/file/2023/3/66573_0s.jpg)
Java的split方法使用详解
![](https://img.aspxhome.com/file/2023/3/64523_0s.png)
Java JDK动态代理(AOP)用法及实现原理详解
![](https://img.aspxhome.com/file/2023/2/69292_0s.png)
jsp、struts、spring、mybatis实现前端页面功能模块化拆分的方案
Java实战入门之双色球彩票小游戏
![](https://img.aspxhome.com/file/2023/6/63486_0s.png)