我刚刚花了一些时间弄清楚 PCRE2 接口(interface),并且认为我已经掌握了它的大部分内容。我想支持 UTF32,pcre2 已经构建支持,码位宽度已设置为 32。
下面的代码是我将代码点宽度设置为 8 时得到的代码。 如何更改它以使用 UTF32?
#include "gtest/gtest.h"
#include <pcre2.h>
TEST(PCRE2, example) {
//iterate over all matches in a string
PCRE2_SPTR subject = (PCRE2_SPTR) string("this is it").c_str();
PCRE2_SPTR pattern = (PCRE2_SPTR) string("([a-z]+)|\\s").c_str();
int errorcode;
PCRE2_SIZE erroroffset;
pcre2_code *re = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, PCRE2_ANCHORED | PCRE2_UTF, &errorcode,
&erroroffset, NULL);
if (re) {
uint32_t groupcount = 0;
pcre2_pattern_info(re, PCRE2_INFO_BACKREFMAX, &groupcount);
pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(re, NULL);
uint32_t options_exec = PCRE2_NOTEMPTY;
PCRE2_SIZE subjectlen = strlen((const char *) subject);
errorcode = pcre2_match(re, subject, subjectlen, 0, options_exec, match_data, NULL);
while (errorcode >= 0) {
PCRE2_UCHAR *result;
PCRE2_SIZE resultlen;
for (int i = 0; i <= groupcount; i++) {
pcre2_substring_get_bynumber(match_data, i, &result, &resultlen);
printf("Matched:%.*s\n", (int) resultlen, (const char *) result);
pcre2_substring_free(result);
}
// Advance through subject
PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data);
errorcode = pcre2_match(re, subject, subjectlen, ovector[1], options_exec, match_data, NULL);
}
pcre2_match_data_free(match_data);
pcre2_code_free(re);
} else {
// Syntax error in the regular expression at erroroffset
PCRE2_UCHAR error[256];
pcre2_get_error_message(errorcode, error, sizeof(error));
printf("PCRE2 compilation failed at offset %d: %s\n", (int) erroroffset, (char *) error);
}
大概subject
和pattern
需要以某种方式进行转换,并且result
将是相同的类型?我在 pcre2 header 中找不到任何表明对此支持的内容。
我猜 subjectlen
将不再只是 strlen
。
最后,我通过浏览一些文档和标题将这个示例放在一起,还有什么我应该做/值得知道的吗?
最佳答案
我最终离开了pcre2,在评估了RE2、PCRE2和ICU后,我选择了ICU。它的 unicode 支持(从我到目前为止所看到的来看)比其他两个更完整。它还提供了一个非常干净的 API 和许多用于操作的实用程序。重要的是,PCRE2 提供了一个 perl 风格的正则表达式引擎,开箱即用,可以很好地与 unicode 配合使用。
关于c++ - PCRE2 UTF32 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019651/