替换匹配的正则表达式的子字符串

Fle*_*exo 6 java regex string removing-whitespace

我获取一些html并进行一些字符串操作,并使用类似的字符串

string sample = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n"
Run Code Online (Sandbox Code Playgroud)

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

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
}
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 3

以下代码应该适合您:

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() + ']');
Run Code Online (Sandbox Code Playgroud)

输出

Final: [2 dl. flour 4 cups of sugar]
Run Code Online (Sandbox Code Playgroud)