gpt4 book ai didi

java - 正则表达式从多行匹配到字符串缓冲区末尾并替换为 ""

转载 作者:行者123 更新时间:2023-11-30 04:11:51 25 4
gpt4 key购买 nike

我有以下文件内容,我正在尝试匹配下面解释的注册表,并将匹配的开头(“On....write”)替换为空白“”到字符串缓冲区的末尾:

-- 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...wrote:”替换到文件末尾: “...:

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

}

关于java - 正则表达式从多行匹配到字符串缓冲区末尾并替换为 "",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19415311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com