2016-05-09 9 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

、私は2つの正規表現でそれを行うだろう呼び出す:

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

私は3番目をテストしました。 (私はJava 7を使用しています)、動作しますが、 'if(!str.isEmpty()){'を追加して、空白でない行だけをトリミングします。ありがとう。 – developer033

関連する問題