Java REGEX 捕获太多

标签 java regex xml tags

我正在尝试实现一个简单的 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 时,它会给我所有的标签,直到它第一次找到“关键字”这个词。所以,问题是这一行:

</title>.*?<description>

我如何告诉我的 REGEX 如果它找到的第一个描述标签没有关键字,它应该选择下一个标签并返回第二个项目标签的结果。或者,如果 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

关于Java REGEX 捕获太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32344811/

相关文章:

java - 使用 JAXB 交叉引用来自两个 XML 文件的 XmlID

regex - 使用正则表达式、kibana 搜索数组中的元素

javascript - 用于使用逗号和空格验证数字的正则表达式

android - 删除菜单图标和标题之间的空格

java - Controller 路径变量绑定(bind)删除结尾空格

java - 获取 com.mongodb.MongoSocketReadException : Prematurely reached end of stream- MongoDB

java.lang.NoClassDefFoundError : com/google/common/base/internal/Finalizer$ShutDown (wrong name: com/google/common/base/internal/Finalizer)

JavaScript 正则表达式从文本文件中获取标题和副标题

java - XML 输出中的编码问题

php - 解析XML文件并将结果插入MySQL