PCRE 简介
介绍PCRE (Perl Compatible Regular Expressions) 是一个用C语言编写的正则表达式函数库。本文简要介绍PCRE的编译和使用方法。 编译从PCRE官网下载后,解压(本人下的版本为pcre2-10.21)。仔细阅读 README 和 NON-AUTOTOOLS-BUILD,里面介绍了很多编译的方法。由于本人需要在VS下开发,因此选择CMake编译。 使用
#include "pcre2.h"
#include <string>
#include <iostream>
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<PCRE2_SPTR>(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<PCRE2_SPTR>(subject.c_str()),subject.length(),start_offset,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;
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |