2

我正在尝试删除字符串中的 LaTeX 注释:

输入字符串:

\begin{comment}inside \n comment 1 \end{comment} 评论外的东西 \begin{comment} inside comment 2 \end{comment} 在评论 2 之后

输出:

\begin{comment}inside comment 1 \end{comment} 在评论 2 之后的一些外部评论

理想的输出:

something outside comments after comment 2

示例代码:

public static void main(String[] args) {
    String input = "\\begin{comment}inside \n comment 1  \\end{comment}  something outside comments \\begin{comment} inside comment 2\\end{comment} after comment 2";
    System.out.println(input.replaceAll("\\\\begin\\{comment\\}(.*|[\\s]*|\\n*)\\\\end\\{comment\\}", ""));
    }

所以问题是这个正则表达式没有检测到\n.

我使用以下链接来形成正则表达式:

http://www.regexplanet.com/advanced/java/index.html

4

1 回答 1

4

Pattern使用该选项编译您的Pattern.DOTALL,或者将等效的标志表达式添加(?s)到您的正则表达式中,以便.匹配\n. 另外,您的正则表达式似乎不起作用,请尝试以下操作:

System.out.println(input.replaceAll("(?s)\\\\begin\\{comment\\}.*?\\\\end\\{comment\\}", ""));
于 2012-08-21T01:02:22.977 回答