2016-05-09 125 views
-1

首先,我想刪除文本中每行的空格。 我現在使用的正則表達式起作用,但它也刪除了應保留的空白行。刪除多行空格

我的正則表達式:

(?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.* 
*************************************************************** 

正如我所說的,它應該只刪除開頭和結尾的空格,但不是空行。

說明:(*) - 表示空格。

+0

爲什麼不直接使用String.trim(如果要排除空行if語句添加)? –

+0

由於修剪刪除空白行。 – developer033

+0

我可以知道downvote的原因嗎? – developer033

回答

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的

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

我認爲你誤解了我的問題。我在開始和結束時說過,我只想刪除尾隨和前導空格,但保留空行。 – developer033

+0

我測試了第三個。 (我在Java 7上),它的工作原理,我只是加了'if(!str.isEmpty()){'只修剪非空白行。謝謝。 – developer033