【发布时间】:2017-04-08 13:19:08
【问题描述】:
我正在尝试使用正则表达式从文件中删除一段文本。
现在我在一个String 中有文件的内容,但Matcher 找不到模式。
示例文件为:
\begin{comment}
this block should be removed
i.e. it need to be replaced
\end{comment}
this block should remains.
\begin{comment}
this should be removed too.
\end{comment}
我需要找到以\begin{comment} 开头并以\end{comment} 结尾的块,然后将它们删除。
这是我使用的最小代码。我正在使用的正则表达式是\\begin\{.*?\\end\{comment\},它应该找到以'\begin' 开头的模式,直到第一次出现'\end{comment}'。我在 Notepad++ 中工作过。
但是使用这个 java 代码,它会找到第一个 '\begin' 和最后一个 '\end' 行并删除它们之间的所有内容。我想保留不在在块中的行。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class main {
public static void main(String[] args) {
String output;
String s = "\\begin{comment}\n"+
"this block should be removed\n"+
"i.e. it need to be replaced\n"+
"\\end{comment}\n"+
"this block should remains.\n"+
"\\begin{comment}\n"+
"this should be removed too.\n"+
"\\end{comment}";
Matcher m = Pattern.compile("\\\\begin\\{comment(?s).*\\\\end\\{comm.*?\\}").matcher(s);
while(m.find())
{
System.out.println(m.group(0));
output = m.replaceAll("");
}
m = Pattern.compile("\\begin").matcher(s);
while(m.find())
{
System.out.println(m.group(0));
output = m.replaceAll("");
}
}
}
更新:
我使用this在线工具找到它。 Matcher m = Pattern.compile("\\begin\{comment(?s).\\end\{comm.?\}").matcher(s);
【问题讨论】: