删除多行空格

时间:2016-05-09 01:44:20

标签: java regex

首先,我想删除文本中每行的空格。 我现在使用的正则表达式可以正常工作,但它也会删除空白行,这应该保留。

我的正则表达式:

(?m)\s+$

我做了一个带有负面观察的测试,但它不起作用。

(?m)(?<!^)\s+$

文字样本:

This text is styled with some of the text formatting properties.**
**The heading uses the text-align, text-transform, and color* 
properties. The paragraph is indented, aligned, and the space*
***************************************************************
*between characters is specified. The underline is removed from*
this colored "Try it Yourself" link.*
***************************************************************

正如我所说,它应该只删除前导和尾随空格,而不是空行。

标题:(*) - 表示空格。

1 个答案:

答案 0 :(得分:1)

要使用正则表达式执行此操作,我将在两个正则表达式调用中执行此操作:

String text = "This text is styled with some of the text formatting properties.  \n"
   + "  The heading uses the text-align, text-transform, and color\n"
   + "\n"
   + "properties. The paragraph is indented, aligned, and the space \n"
   + "     \n";
String result = text.replaceAll("(?m)^\\s+", "").replaceAll("(?m)\\s+$", "");

我不会使用正则表达式。我会使用拆分来获取每条线然后修剪。我不清楚你是否想要包含空白行。 (你的帖子说你希望它们被排除在外,但你的评论说你希望它们被包含在内。)这只是删除过滤器的问题。

String result = Pattern.compile("\n").splitAsStream(text)
   .map(String::trim)
   .filter(s -> ! s.isEmpty())
   .collect(Collectors.joining("\n"));      

如果您使用的是Java 7(如果要排除空行,​​请添加if语句)

String[] lines = text.split("\n");
StringBuilder buffer = new StringBuilder();
for (String line : lines) {
   buffer.append(line.trim());
   buffer.append("\n");
}
String result = buffer.toString();
相关问题