我获取一些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]