【问题标题】:java regex detect \njava 正则表达式检测\n
【发布时间】:2012-08-16 08:17:01
【问题描述】:

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

输入字符串:

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

输出:

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

理想的输出:

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

【问题讨论】:

    标签: java regex latex newline replaceall


    【解决方案1】:

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

    System.out.println(input.replaceAll("(?s)\\\\begin\\{comment\\}.*?\\\\end\\{comment\\}", ""));
    

    【讨论】:

    • System.out.println(input.replaceAll("(?m)\\\\begin\\{comment\\}(.*|[\\s]*|\\n* )\\\\end\\{comment\\}", ""));给出相同的结果...还尝试了 Pattern p = Pattern.compile("\\\\begin\\{comment\\}(.*|[\\s]*|\\n*)\\\\end \\{评论\\}”); System.out.println(input.replaceAll(p.toString(), ""));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 1970-01-01
    • 2015-12-29
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-07
    相关资源
    最近更新 更多