介绍
PCRE (Perl Compatible Regular Expressions) 是一个用C语言编写的正则表达式函数库。本文简要介绍PCRE的编译和使用方法。
编译
使用
- 建立工程的时候需要配置字符长度,例如定义宏 PCRE2_CODE_UNIT_WIDTH=8
- 如果使用静态库,需要定义宏 PCRE2_STATIC
- 这里仅列出简单的使用说明,具体的API使用方法详见API说明文档。
-
#include "pcre2.h" #include#include int main(void) { const std::string pattern{ "\\d{3,5}" }; int error_code = 0; PCRE2_SIZE error_offset = 0; pcre2_code *code = pcre2_compile(reinterpret_cast (pattern.c_str()), PCRE2_ZERO_TERMINATED, 0, &error_code, &error_offset, NULL); if (code == NULL) { return -1; } const std::string subject{ "tel1:1234;tel2:3456;tel3:5678" }; pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(code, NULL); int rc = 0; int start_offset = 0; unsigned int match_index = 0; while ((rc = pcre2_match(code, reinterpret_cast (subject.c_str()), subject.length(), start_offset, 0, match_data, NULL)) > 0) { PCRE2_SIZE *ovector = pcre2_get_ovector_pointer(match_data); int i = 0; for (i = 0; i < rc; i++) { std::cout << "match " << ++match_index << ": " << std::string(subject.c_str() + ovector[2*i], ovector[2*i + 1] - ovector[2*i]) << std::endl; } start_offset = ovector[2*(i-1) + 1]; } return 0; }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/203309.html原文链接:https://javaforall.net
