我试图找到一种方法来将C++中的字符串与XML正则表达式相匹配。XML正则表达式语法不受std::regex支持,因此我安装了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;
}输出:不匹配。
如果我编写了一个非常简单的正则表达式,它不使用字符类减法,它看起来确实有效。但问题是,我需要字符类减法来工作,因为我需要支持符合语法的任何可能的regex。
Xerces的文档非常不清楚,没有指定这个函数使用哪种regex语法,但我假设它是一个XML解析库,它将实现XML正则表达式。也许这个假设是错误的?
编辑:
从我需要支持的XSD文件中添加一个实际regex的示例。此示例来自定义XML架构支持的基本数据类型的架构。规范可以在这里找到:https://www.w3.org/TR/xmlschema-2/#conformance
我需要解析一个使用字符类减法(以及特殊的\c和\i字符组)的正则表达式示例,如下所示,"NCName“数据类型的xs:pattern限制如下:
<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>发布于 2021-03-21 01:40:47
好的,所以我无法让Xerces正则表达式工作,而文档就差得很远,所以我决定尝试另一个库。libxml2有XML正则表达式,尽管regex特性的文档也同样糟糕,但我还是能够得到一个工作程序。
#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++中工作的相同问题。
https://stackoverflow.com/questions/66716696
复制相似问题