簡體   English   中英

RegEx從多行匹配到字符串緩沖區的末尾,並替換為“”

[英]RegEx match from a multi line to end of string buffer and replace with “”

我具有以下文件內容,並且嘗試匹配下面說明的reg,並將匹配項的開頭(“ On .... wrote”)替換為字符串緩沖區的末尾用空白“”:

-- file.txt (Before regx match and replace) -- 
test

On blah

more blah wrote:

So, this should be stripped all out and all that left should be the above test contents.
-- EOF -- 


-- file.txt (After regex mach and replace) -- 
test
-- EOF -- 

如果我從上方將文件內容讀取為字符串,然后嘗試匹配“ On ... wrote:”部分,則似乎無法從“ On ... writted:”替換文件末尾。 。:

    // String text = <file contents from above...the Before contents>
    Pattern PATTERN = 
      Pattern.compile("^(On\\s(.+)wrote:)$", Pattern.MULTILINE | Pattern.DOTALL );
    Matcher m = PATTERN.matcher(text);
    if (m.find()) {
       // This matches but I want to strip from "On....wrote:  -> <end of string>
       text = m.replaceAll("");  // This should only contain "test"

    }

您不需要進行比賽,就可以直接替換。 如果替換中使用的模式不匹配,則不會發生任何事情。

請嘗試以下操作:

// String text = <file contents from above...the Before contents>
String text = text.replaceAll("^(On.*?wrote:).*$", "");

注意:您可能需要從正則表達式內部打開Pattern.MULTILINEPattern.DOTALL的標志,您可以這樣操作:

String text = text.replaceAll("(?sm)^(On.*?wrote:).*$", "");

編輯:當然,您可以:

// String text = <file contents from above...the Before contents>
Pattern PATTERN = 
  Pattern.compile("^(On.*?wrote:).*$", Pattern.MULTILINE | Pattern.DOTALL );
Matcher m = PATTERN.matcher(text);
if (m.find()) {
   text = m.replaceAll("");  // This should only contain "test"

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM