Java replaceall 不会用通配符的一种走弯路解决方式
碰到这样一个问题,对于已经处理好的字符串,如“我【 最 满意 的 一点 】 老婆 喜欢 【 最 不 满意 的 一点 】 大灯 没有 透镜 ! 比 我 4 年前 的 fortow 还 low , 而且 没有 自动 大灯 , 自动 雨刷 【 空间 】 微型车 , 就 这样 吧 。”,想把里面所有带【】的内容去掉,并替换成“xx”。首先想到的是用通配符,如下面代码所示:
public static void main(String[] args) {
// TODO Auto-generated method stub
String Str = new String("我【 最 满意 的 一点 】 老婆 喜欢 【 最 不 满意 的 一点 】 大灯 没有 透镜 ! 比 我 4 年前 的 fortow 还 low , 而且 没有 自动 大灯 , 自动 雨刷 【 空间 】 微型车 , 就 这样 吧 。");
System.out.println(Str.replaceAll("【(.*)】", "xx" ));
}
返回结果为:
匹配成功返回值 :我xx 微型车 , 就 这样 吧 。
系统的处理方式是找到最开始的【和最后的】,然后将其整个的替换成了“xx”,显然不是我想要的结果。
后来想到一种办法,就是对于【】的配对,一个一个的找,找到了就进行替换。
修改后的代码如下:
public static void main(String[] args) {
// TODO Auto-generated method stub
String hahaha = "【 最 满意 的 一点 】 老婆 喜欢 【 最 不 满意 的 一点 】 大灯 没有 透镜 ! 比 我 4 年前 的 fortow 还 low , 而且 没有 自动 大灯 , 自动 雨刷 【 空间 】 微型车 , 就 这样 吧 。 "
String aaa = null;
Boolean judge = true;
while(judge) {
if(hahaha.contains("【")) {
String hhh = hahaha.substring(hahaha.indexOf("【"),hahaha.indexOf("】")+1);
hahaha = hahaha.replaceAll(hhh, ",");
}
else judge = false;
System.out.println(hahaha);
}
通过这个处理,就完成了我本来想完成的事情!方法也行很low,但是解决了问题。