c++ - C语言 正则表达式结果不对?

查看:134
本文介绍了c++ - C语言 正则表达式结果不对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在linux平台下,使用c++11正则表达式错误。。

bool isPattern(string str,string pattern)
{
     bool tag=false;
    if(str.size() > 0 && pattern.size() >0)
    {
        string match;
        regex_t reg;
        char errbuf[1024];
        char *buff=new char[str.size()];
        int err=0;
        int nm=1024;
        memcpy(buff,str.c_str(),str.size());
        regmatch_t pmatch[nm];
        if(regcomp(&reg,pattern.c_str(),REG_NEWLINE|REG_EXTENDED) < 0){
        regerror(err,&reg,errbuf,sizeof(errbuf));
        cout<<errbuf<<endl;
        }
    err=regexec(&reg,buff,nm,pmatch,0);
    if(err==REG_NOMATCH) {
        cout<<"no match"<<endl;
    }
     else if(err)
    {
        regerror(err,&reg,errbuf,sizeof(errbuf));
        cout<<errbuf<<endl;

    }
    else
    {
        int len=0;
        for(int i=0;i<nm && pmatch[i].rm_so!=-1;++i)
        {
            len=pmatch[i].rm_eo-pmatch[i].rm_so;
            if(len > 0)
            {
                match.clear();
                match.assign(buff+pmatch[i].rm_so,len);
                cout<<"匹配结果:"<<match<<endl;
                tag=true;
        //      match.clear();
            }
        }
        regfree(&reg);

     }
    delete [] buff;
  }
    return tag;
}
                            

原始字符串
string str="huangyong"urlname:" "三明治"h good way "urlname:" "蔬菜"h hello world "urlname:"h "apple", wiofjofiewajoi";
正则表达式
string pattern=""urlname:".*?"";
程序运行结束后,输出的结果是:匹配结果:"urlname:" "三明治"h good way "urlname:" "蔬菜"h hello world "urlname:"h "apple"
这个正则表达式通过在线测试工具是正确的,但是输出的结果却不是想要的。
各位大神,求助啊。。

解决方案

~~ 好吧,众审真是个扯淡的功能。
使用正则表达式最好使用c++11提供的raw string去除转义字符的干扰。
还有题目的标签是非常重要的,不要乱贴。。

这篇关于c++ - C语言 正则表达式结果不对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆