6

我获取一些 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分升。面粉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
}
4

6 回答 6

4

sample = sample.replaceAll("[\\n ]+", " ").trim();

输出:

2 dl. flour 4 cups of sugar

开头没有空格,结尾也没有空格。

它首先用一个空格替换所有空格和换行符,然后从 begging / end 修剪多余的空格。

于 2011-05-26T19:38:06.543 回答
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() + ']');

输出

Final: [2 dl. flour 4 cups of sugar]
于 2011-05-26T20:06:44.687 回答
1

我认为这样的事情对你有用:

String test = "\n    \n   2 \n      \n  \ndl. \n \n    \n flour\n\n     \n 4   \n    \n cups of    \n\nsugar\n";

/* convert all sequences of whitespace into a single space, and trim the ends */
test = test.replaceAll("\\s+", " ");
于 2011-05-26T19:38:02.313 回答
1

我认为这\n不是实际的换行符,但它也适用于linefeeds. 这应该可以正常工作:

test=test.replaceAll ("(?:\\s|\\\n)+"," ");

如果没有textual \n,它可以更简单:

test=test.replaceAll ("\\s+"," ");

您需要修剪前导/尾随空格。

我使用 RegexBuddy 工具检查任何单个正则表达式,在这么多语言中非常方便。

于 2011-05-26T21:20:18.927 回答
0

您应该能够使用标准String.replaceAll(String, String)。第一个参数将采用您的模式,第二个参数将采用空字符串。

于 2011-05-26T19:22:44.367 回答
0
s/^\s+//s
s/\s+$//s
s/(\s+)/ /s

运行这三个替换(用空替换前导空格,用空替换尾随空格,用空格替换多个空格。

于 2011-05-26T19:26:16.533 回答