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

前端之家收集整理的这篇文章主要介绍了java – 替换匹配的正则表达式的子串前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
获取一些html并进行一些字符串操作,并使用类似的字符串
string sample = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n"

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

2 dl.面粉和4杯糖

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

Pattern p = Pattern.compile("[\\d]+[\\s\\w\\.]+");
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 flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n";
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]

猜你在找的Java相关文章