加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 替换匹配的正则表达式的子串

发布时间:2020-12-14 05:53:16 所属栏目:Java 来源:网络整理
导读:我获取一些html并进行一些字符串操作,并使用类似的字符串 string sample = "n n 2 n n ndl. n n n flournn n 4 n n cups of nnsugarn" 我想找到所有成分线并删除空格和换行符 2 dl.面粉和4杯糖 到目前为止,我的方法如下. Pattern p = Patter
我获取一些html并进行一些字符串操作,并使用类似的字符串
string sample = "n    n   2 n      n  ndl. n n    n flournn     n 4   n    n cups of    nnsugarn"

我想找到所有成分线并删除空格和换行符

2 dl.面粉和4杯糖

到目前为止,我的方法如下.

Pattern p = Pattern.compile("[d]+[sw.]+");
Matcher m = p.matcher(Result);

while(m.find()) {
  // This is where i need help to remove those pesky whitespaces
}

解决方法

以下代码应该适合您:
String sample = "n    n   2 n      n  ndl. n n    n flournn     n 4   n    n cups of    nnsugarn";
Pattern p = Pattern.compile("(s+)");
Matcher m = p.matcher(sample);
sb = new StringBuffer();
while(m.find())
    m.appendReplacement(sb," ");
m.appendTail(sb);
System.out.println("Final: [" + sb.toString().trim() + ']');

OUTPUT

Final: [2 dl. flour 4 cups of sugar]

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读