Java 删除多行空间

Java 删除多行空间,java,regex,Java,Regex,首先,我想删除文本中每行的空格。 我现在使用的正则表达式可以工作,但它也删除了应该保留的空行 我的正则表达式: (?m)\s+$ 我做了一个负回溯测试,但它不起作用 (?m)(?<!^)\s+$ 正如我所说,它应该只删除前导空格和尾随空格,而不是空行 说明:(*)-表示空白。要使用正则表达式执行此操作,我将在两个正则表达式调用中执行此操作: String text = "This text is styled with some of the text formatting prope

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

我的正则表达式:

(?m)\s+$
我做了一个负回溯测试,但它不起作用

(?m)(?<!^)\s+$
正如我所说,它应该只删除前导空格和尾随空格,而不是空行


说明:(*)-表示空白。

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

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 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.trim?因为trim会删除空行。我可以知道downvote的原因吗?如果String.length()>0 String.trim();为什么不直接使用String.trim?因为trim会删除空行。我可以知道downvote的原因吗?如果String.length()>0 String.trim();我想你误解了我的问题。我在开头和结尾都说过,我只想删除尾随空格和前导空格,但保留空行。我测试了第三个。way(我在Java 7上)是有效的,我只是添加了
if(!str.isEmpty()){
来只修剪非空行。谢谢。我想你误解了我的问题。我在开始和结束时都说过,我只想删除尾随空格和前导空格,但保留空行。我测试了第3.way(我在Java 7上)并且它有效,我只是添加了
if(!str.isEmpty()){
只修剪非空行。谢谢。