Java REGEX 捕获过多

Java REGEX Capturing too much

我正在尝试实现一个简单的 REGEX,它允许我在 XML 中捕获一些信息。

但是,我的 REGEX 捕获了几个标签并给了我一个很长的答案。例如,如果我有类似的东西:

<item>
<title>bla</title>
...
<description>bla</description>
</item>
<item>
<title>bla2</title>
....
<description>bla2, keyword here are blablabla</description>
</item>

但是,我使用的正则表达式如下:

<item><title>([\p{L}\p{N}\W \.\,]*?)</title>.*?<description>[\p{L}\p{N} \.\,]keyword[\p{L}\p{N} \.\,]*</description>

标题和描述之间有标签。当我使用那个 REGEX 时,它会给我所有的标签,直到它第一次找到单词 "keyword"。所以,问题是这一行:

</title>.*?<description>

我如何告诉我的 REGEX 如果它找到的第一个描述标签没有关键字,它应该 select 下一个标签和 return 第二个项目标签的结果。或者,如果 title 标签和 description 标签之间有一个结束项目标签,它不应该查找所有数据。

我希望我解释清楚了。如果需要,请要求澄清。

编辑:

另一种解决方案:

 <item><title>([\p{L}\p{N}\W \.\,]*?)</title>(?:(?!<item>).)*?<description>[\p{L}\p{N} \.\,]keyword[\p{L}\p{N} \.\,]*</description>

使用 (?:(?!).)* 作为否定前瞻以避免在新项目中捕获字符串。

这个正则表达式怎么样?

(<item>[^<]*?<title>(?<title>[^<]*?)<\/title>([^<]|<(?!description))*<description>(?<desc>[^<]*?keyword[^<]*?)<\/description>[^<]*?<\/item>)

它匹配每个项目并捕获描述和标题。之后您可以循环匹配并找到包含您的关键字的项目。

import java.util.regex.Pattern;
import java.util.regex.Matcher;
class Module1{
  public static void main(String[] asd){
      String sourcestring = "source string to match with pattern";
      Pattern re = Pattern.compile("(<item>[^<]*?<title>(?<title>[^<]*?)<\/title>([^<]|<(?!description))*<description>(?<desc>[^<]*?keyword[^<]*?)<\/description>[^<]*?<\/item>)",Pattern.DOTALL);
      Matcher m = re.matcher(sourcestring);
      int mIdx = 0;
      while (m.find()){ 
          for( int groupIdx = 0; groupIdx < m.groupCount()+1; groupIdx++ ){
            System.out.println( "[" + mIdx + "][" + groupIdx + "] = " +    m.group(groupIdx));
      }
      mIdx++;
    }
  }
}

您可以在此处找到示例数据的结果:https://regex101.com/r/gA3nR4/4