关于C++ regex遇到的问题

一. 段错误 现象

代码:

smatch result;
string reg("waitInput[\(]\"([0-9])\",\"([A-Z]+)\"[\)]");
cout << "regular:" << reg << endl;
regex pattern(reg, regex::icase);
cout << "2" << endl;
string str2 =str;bool ismatch = regex_match(str, result, pattern);
if(!ismatch) {cout << "No match" << endl;
} else if (ismatch) {//counts = result.size();cout << "Exchange waitInput:" << endl;smatch::iterator it = result.begin() + 1;int i = 0;for(;it != result.end(); it++, i++) {cout << it->str() << endl;}
}

如上的代码块,同样的匹配规则和程序调用,当第二次调用的时候会出现段错误,已经定位为regex_match内部的原因,因为我把正则规则替换为如下,则完全没有问题:

string reg("waitInput[\(][\)]");

曾经尝试过,使用regex_research进行操作:

regex_search(str2, result, pattern);
for(auto x:result) cout << x << " ";
cout << endl;

仍旧是一样的段错误

使用gdb调试:

Thread 10 "hulk5" received signal SIGSEGV, Segmentation fault.
[Switching to LWP 747]
std::bitset<256u>::_Unchecked_test (this=0x0, __pos=0) at /home/illusion/workspace/toolchains/gcc-linaro-arm-linux-gnueabihf-5.3/arm-linux-gnueabihf/include/c++/5.3.1/bitset:1057
1057	/home/illusion/workspace/toolchains/gcc-linaro-arm-linux-gnueabihf-5.3/arm-linux-gnueabihf/include/c++/5.3.1/bitset: No such file or directory.
std::_Any_data::_M_access, false, false> > (this=0x0)at /home/illusion/workspace/toolchains/gcc-linaro-arm-linux-gnueabihf-5.3/arm-linux-gnueabihf/include/c++/5.3.1/functional:1608
1608	/home/illusion/workspace/toolchains/gcc-linaro-arm-linux-gnueabihf-5.3/arm-linux-gnueabihf/include/c++/5.3.1/functional: No such file or directory.

主要是以上两个问题,至今没有找到合适的解决办法。

二. 解决方案

使用c 中的 进行替换即可。

int Split_string_by_regex_c(string str_regex, string str, char data[][100])
{int counts = 0;int status ,i;int cflags = REG_EXTENDED;regmatch_t pmatch[10];const size_t nmatch = 10;regex_t reg;char match[100];//char data[nmatch][100];char str_m[100];strncpy(str_m, str.c_str(), 100);memset(data,0x0,nmatch * 100);//const char *pattern = "waitInput[\(]\"([0-9])\",\"([A-Z]+)\"[\)]";const char *pattern = str_regex.c_str();regcomp(®, pattern, cflags);//编译正则模式status = regexec(®, str_m, nmatch, pmatch, 0);//执行正则表达式和缓存的比较if(status == REG_NOMATCH) {//printf("No match\n");} else if (0 == status) {for(int i= 0; i < 10 && pmatch[i].rm_so != -1; i++){int len = pmatch[i].rm_eo - pmatch[i].rm_so;//printf("i %d => len:%d\n",i,len);if(len) {counts ++;memset(match, '\0', sizeof(match));memcpy(match, str_m + pmatch[i].rm_so,len);// get axis distance speed acc from i == 1//printf("match %d:%s\n",i,match);if(i >= 0) {memcpy(data[i], match, len);//printf("length:%d\n",strlen(data[i]));//printf("data[%d]:%s\n",i,data[i]);}}}}return counts;
}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部