2013-11-04 39 views
0

我有以下文件內容和我試圖在每一行的開頭相匹配一個reg-EX用於字符的連續的塊(具體「>」),併除去文本相匹配的該塊:如何在換行符上匹配'>'的連續字符塊?

-- file.txt (Before regx match and replace) -- 
keep this 

> remove this 
> 
> remove this too 
-- EOF -- 


-- file.txt (After regex mach and replace) -- 
keep this 

-- EOF -- 

我試圖匹配這個多行(即刪除任何以'>'開頭的行)。這是正確的還是最好的方法?以下似乎沒有工作。

// String text = <file contents from above...the Before contents> 
    Pattern PATTERN = 
     Pattern.compile("^>(.*)$", Pattern.MULTILINE); 
    Matcher m = PATTERN.matcher(text); 
    if (m.find()) { 
     // Matches each line starting with > and deletes (replaces with "") the line 
     text = m.replaceAll(""); 

    } 
+2

你是什麼意思,當你說它不工作?出了什麼問題? –

回答

2

@Peter Alfvin所述,您需要在您的替換中包含您的換行符\n

text = text.replaceAll("(?m)^>[^>]*?\n", ""); 

正則表達式:

(?m)   set flags for this block (with^and $ matching start and end of line) 
^    the beginning of a "line" 
>    '>' 
[^>]*?  any character except: '>' (0 or more times) 
       (matching the least amount possible)) 
\n   '\n' (newline) 

(?m)改性劑(多線)導致^$到每一行的開始/結束相匹配。

請參閱working demo

+0

太棒了!謝謝! – JaJ

2

您需要通過最終的線(\n),而不是隻到它($)以完全刪除這些行的匹配。

相關問題