gcc 4.8中已经包含了std regex的头文件
可是没有实现,所以链接是失败的
gcc 4.9完整的支持了c++ 11的regex。
在4.9以前,可以寻求boost的regex。
不过,我更熟悉pcre,基于perl的正则表达式的实现。
下载源码,解压
将库配置为交叉编译,只生成静态库,配置pcre代码如下:
#!/bin/sh export ROOTDIR="${PWD}"
cd pcre-8.36/ export CROSS_COMPILE="arm-linux-androideabi" export AR=${CROSS_COMPILE}-ar
export AS=${CROSS_COMPILE}-as
export LD=${CROSS_COMPILE}-ld
export RANLIB=${CROSS_COMPILE}-ranlib
export CC=${CROSS_COMPILE}-gcc
export CXX=${CROSS_COMPILE}-g++
export NM=${CROSS_COMPILE}-nm ./configure --prefix=${ROOTDIR}/build/pcre --target=${CROSS_COMPILE} --host=${CROSS_COMPILE} --build=i686-linux --disable-shared
执行make && make install 编译生成目标文件
接下来我们开始使用libpcre库
枚举所有匹配的项,并将结果打印出来,代码如下:
#include "pcre.h"
#include <string>
#include <vector>
#include <iostream> int main(void)
{
const int OVECCOUNT = ;
std::string src_string = "Saturday=6 and Sunday=7, but some Fridays=5 joke=102 also.";
std::string regex_string = "\\w+=\\d+";
bool b_case = false; const char* error;
int erroffset;
int ovector[OVECCOUNT];
std::vector<std::string> sfinds;
pcre* re = pcre_compile(regex_string.c_str(), b_case ? PCRE_CASELESS : ,
&error, &erroffset, NULL);
if(re)
{
unsigned int offset = ;
unsigned int len = src_string.size();
const char* str = src_string.c_str();
int rc = ;
while(offset < len && (rc = pcre_exec(re, , str, len, offset, , ovector, OVECCOUNT)) >= )
{
std::cout << "find count: " << rc << std::endl;
for(int i = ; i < rc; ++i)
{
int s_len = ovector[*i+] - ovector[*i];
std::string sfind = src_string.substr(ovector[*i], s_len);
sfinds.push_back(sfind);
}
offset = ovector[];
} pcre_free(re);
} for(size_t i = ; i < sfinds.size(); ++i)
std::cout << "*" <<sfinds[i] << "* ";
std::cout << std::endl; return ;
}
编译运行regex,输出结果为:
find count: 1
find count: 1
find count: 1
find count: 1
*Saturday=6* *Sunday=7* *Fridays=5* *joke=102*