如何捕获捕获子组

时间:2016-04-28 06:28:49

标签: java regex

我有一些文字如下:

Postprandial Data

Reflux Episode Activity (Impedance)
            Total   Normal

    Postprandial Analysis Settings

Symptom Correlation to Reflux (Impedance)

我想在Symptom Correlation to Reflux (Impedance)

之前找到并删除所有内容

我很遗憾地使用以下代码删除Symptom Correlation to Reflux (Impedance)。我怎么能保留它?我尝试了group(0)group(1)

Pattern goPP = Pattern.compile("(Postprandial Data.*)Symptom Correlation to Reflux",Pattern.DOTALL);
            Matcher goPP_pattern = goPP.matcher(s);
            //This splits the original document into the Main stuff and the postprandial stuff so extraction should be more straightforward
            String PPStr="";
                        while (goPP_pattern.find()) {
                   for (String df:goPP_pattern.group(1).split("\n")){
                        PPStr=PPStr+df+"\n";
                    s = s.replace(df,"");
                   }
                 }

1 个答案:

答案 0 :(得分:3)

这个正则表达式足以满足您的需求

(?s)Postprandial Data.*?(?=Symptom Correlation to Reflux \(Impedance\))

<强> Regex Demo

Java代码

System.out.println(ln.replaceAll("(?s)Postprandial Data.*?(?=Symptom Correlation to Reflux \\(Impedance\\))", ""));

<强> Ideone Demo