1

我有以下文件内容,我正在尝试匹配下面解释的 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 ... write:”替换文件末尾。 .:

    // 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"

    }
4

1 回答 1

2

不需要做匹配,直接替换即可。如果替换中使用的模式不匹配任何东西,那么什么都不会发生。

尝试以下操作:

// 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"

}
于 2013-10-16T23:03:05.337 回答