Java 如何匹配'&燃气轮机';在newline上?
我有以下文件内容,我正在尝试在每行开头为字符的连续块(特别是“>”)匹配reg ex,并删除该匹配文本块:Java 如何匹配'&燃气轮机';在newline上?,java,regex,Java,Regex,我有以下文件内容,我正在尝试在每行开头为字符的连续块(特别是“>”)匹配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 -- 我正在尝试将其与多行匹
-- 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("");
}
//字符串文本=
图案图案=
Pattern.compile(“^>(.*)”,Pattern.MULTILINE);
Matcher m=模式匹配器(文本);
if(m.find()){
//匹配以>开头的每一行并删除(替换为“”)该行
text=m.replaceAll(“”);
}
为了完全删除这些行,您需要通过行尾(\n
)匹配,而不仅仅是到它($
)匹配。为了完全删除这些行,您需要通过行尾(\n
)匹配,而不仅仅是到它($
)匹配。如前所述,您需要在替换中包含换行符\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)
修饰符(多行)使^
和$
匹配每行的开始/结束
如前所述,您需要在替换中包含换行符\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)
修饰符(多行)使^
和$
匹配每行的开始/结束
看你说它不起作用是什么意思?出了什么问题?你说它不起作用是什么意思?出了什么问题?