【问题标题】:Replace a block of text using a pattern of Regex (in java)使用 Regex 模式替换文本块(在 java 中)
【发布时间】: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);

【问题讨论】:

    标签: java regex


    【解决方案1】:

    您必须在 2 点上修复您的代码:

    1. 模式应该与您的 Notepad++ 等效模式一致,星号 后面应该跟?懒惰

      Matcher m = Pattern.compile("\\\\begin\\{comment}(?s).*?\\\\end\\{comment}").matcher(s);
      -------------------------------------------------------^
      

    请注意,此模式仅在不存在嵌套注释部分时才能正常工作。

    1. 后一个修复涉及逻辑:如果您调用匹配器 replaceAll 函数,它会在执行时替换 每个 匹配部分(已经在第一个 m.find() 循环执行时)。如果您需要循环检查每个注释块,请将其替换为:

      output = m.replaceFirst("");
      

      或者直接应用output = m.replaceAll("");,没有任何循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      相关资源
      最近更新 更多