java - 将 XML 的正则表达式部分与 java 匹配时出现问题

标签 java regex xml

您好,我在 Java 中使用正则表达式时遇到问题。

我正在尝试解析这个:

*whatever string*
<AttributeDesignator AttributeId="MyIDToParse"
DataType="http://www.w3.org/2001/XMLSchema#string"
Category="theCategoryIWantToParse"
MustBePresent="false"
/>
*whatever string that may contain the same regular expression*

使用此代码(模式+匹配器)

Pattern regex = Pattern.compile("AttributeDesignator +AttributeId=\"(.+)\" +.*Category=\"(.+)", Pattern.DOTALL);
Matcher matcher = regex.matcher(xml);
while (matcher.find()) {
    String ID = matcher.group(1);
    String Category = matcher.group(2);

输出如下:

第 1 组:

MyIDToParse"
    DataType="http://www.w3.org/2001/XMLSchema#string"
    Category="theCategoryIWantToParse"
    MustBePresent="false"
    />
    *whatever string that may contain the same regular expression*

组2:

theCategoryIWantToParse"
    MustBePresent="false"
    />
    *whatever string that may contain the same regular expression*

我觉得这很简单,但我找不到我做错的地方.. 当我在网站中使用正则表达式来测试它们时,它可以正常工作并突出显示 xml 条目中的正确表达式。

最佳答案

尝试使用非贪婪正则表达式。

    Pattern regex = Pattern.compile("AttributeDesignator AttributeId=\"(.+?)\".*Category=\"(.+?)\"", Pattern.DOTALL);

关于java - 将 XML 的正则表达式部分与 java 匹配时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31805483/

相关文章:

java - 键盘打开时自定义操作栏隐藏

xml - 使用/包含来自另一个节点的值

c++ - 在没有附加库的情况下在标准 C/C++ 中解析 XML

java - 简化 if 语句

java - Java多线程同步用法

java - 在多线程环境中并行执行每个子任务

c# - 解析器识别正则表达式时出错

java - 使用java基于查询从elasticsearch获取数据

java - 使用正则表达式对 Java 中的字符串进行词法分析

regex - 使用 nginx 重定向捕获的正则表达式组