微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Xerces-C++ XMLString::patternMatch() 运行不正常

如何解决Xerces-C++ XMLString::patternMatch() 运行不正常

我正在尝试找到一种方法来将 C++ 中的字符串与 XML Schema 正则表达式进行匹配。 std::regex 不支持 XML Schema regex grammar,因此我安装了 Xerces-C++ XML 库以使用其模式匹配功能。不幸的是,即使有一个基本的例子,它似乎也不能正常工作。

#include <iostream>
#include <xercesc/util/XMLString.hpp>

using namespace XERCES_CPP_NAMESPACE;

int main()
{
    try
    {
        XMLPlatformUtils::Initialize();
    }
    catch (const XMLException& ex)
    {
        char* message = XMLString::transcode(ex.getMessage());
        std::cerr << "Error during Xerces-c Initialization.\n"
            << "  Exception message:"
            << message;
        XMLString::release(&message);
        return 1;
    }

    const XMLCh* str = XMLString::transcode("bcdfg");

    // Implement a simple regex that uses "character class subtraction"
    // Should match any string that does not contain vowels
    const XMLCh* pattern = XMLString::transcode("[a-z-[aeiuo]]+");

    if (XMLString::patternMatch(str,pattern) != -1)
    {
        std::cout << "Match!" << std::endl;
    }
    else
    {
        std::cout << "No match." << std::endl;
    }

    XMLPlatformUtils::Terminate();
    return 0;
}

输出 不匹配。

如果我编写一个非常简单的正则表达式,它不使用字符类减法,它似乎确实有效。但问题是我需要字符类减法才能工作,因为我需要支持符合 XML Schema regex 语法的任何可能的正则表达式。

Xerces 的文档非常不清楚,也没有指定此函数使用哪种正则表达式语法,但我假设它是一个 XML 解析库,它将实现 XML 正则表达式。也许那个假设是错误的?

编辑:

从我需要支持的 XSD 文件添加实际正则表达式的示例。此示例来自定义 XML 模式支持的基本数据类型的模式。可以在此处找到规范:https://www.w3.org/TR/xmlschema-2/#conformance

我需要解析的使用字符类减法的正则表达式示例(以及特殊的 \c\i 字符组显示xs:pattern 限制中下面的“NCName”数据类型:

  <xs:simpleType name="NCName" id="NCName">
    <xs:annotation>
      <xs:documentation source="http://www.w3.org/TR/xmlschema-2/#NCName"/>
    </xs:annotation>
    <xs:restriction base="xs:Name">
      <xs:pattern value="[\i-[:]][\c-[:]]*" id="NCName.pattern">
        <xs:annotation>
          <xs:documentation
               source="http://www.w3.org/TR/REC-xml-names/#NT-NCName">
            pattern matches production 4 from the Namespaces in XML spec
          </xs:documentation>
        </xs:annotation>
      </xs:pattern>
    </xs:restriction>
  </xs:simpleType>

解决方法

好的,所以我无法让 Xerces 正则表达式工作,而且文档非常糟糕,所以我决定尝试另一个库。 libxml2 有 XML 正则表达式,虽然正则表达式功能的文档同样糟糕透顶,但我还是能够得到一个可以运行的程序。

#include <iostream>
#include <libxml/xmlregexp.h>

int main()
{
    LIBXML_TEST_VERSION;

    xmlChar* str = xmlCharStrdup("bcdfg");
    xmlChar* pattern = xmlCharStrdup("[a-z-[aeiou]]+");
    xmlRegexp* regex = xmlRegexpCompile(pattern);

    if (xmlRegexpExec(regex,str) == 1)
    {
        std::cout << "Match!" << std::endl;
    }

    free(regex);
    free(pattern);
    free(str);
}

输出:

匹配!

我想即使它没有回答如何让正则表达式与 Xerces 一起正常工作,但这个答案可能会帮助那些正在寻求解决让 XML 模式正则表达式在 C++ 中工作的相同问题的其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。