从 java StringBuilder 中删除子字符串

Removing substrings from java StringBuilder

我想从以下字符串中删除所有 IP 信息。

StringBuilder s=new StringBuilder("Comment by : hihi(ip:1.23.34.5)
                Comment by : rohi(ip:1.23.48.45)
                Comment by : ro 
                Comment by : rosehi(ip:12.39.80.345)Tue Jul 30 10:06:31 EDT 2019 
                Comment by : YES(ip:1.23.72.4345) 
                Comment by : kuhTue Jul 30 10:38:24 EDT 2019
                Comment by : testipcomment(ip:12.56.7.3345)");

预期输出:-

"Comment by : hihi
 Comment by : rohi
 Comment by : ro 
 Comment by : rosehiTue Jul 30 10:06:31 EDT 2019 
 Comment by : YES 
 Comment by : kuhTue Jul 30 10:38:24 EDT 2019
 Comment by : testipcomment"

使用正则表达式

Pattern p = Pattern.compile("\(ip:\d+\)");
Matcher m = p.matcher(s);
System.out.println(m.replaceAll(""));

ip:\\d+ 匹配 ip 后跟任意数字。

下面的代码会给你想要的结果。

    StringBuilder s = new StringBuilder("Comment by : hihi(ip:123345)Comment by : rohi(ip:1234845)Comment by : ro Comment by : rosehi(ip:123980345)Tue Jul 30 10:06:31 EDT 2019 Comment by : YES(ip:123724345) Comment by : kuhTue Jul 30 10:38:24 EDT 2019Comment by : testipcomment(ip:125673345)");
    String str = s.toString().replaceAll("\(ip:\d+\)", "");
    System.out.println(str);