免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2578 | 回复: 2
打印 上一主题 下一主题

求救:正则表达式匹配字符串问题(C++) [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-06-19 19:54 |只看该作者 |倒序浏览


现在要匹配这样一个字符串
AAAA   ddddddd   回车
12345  回车
BBBB   回车
我要从中匹配是否存在AAAA,而且也存在BBBB,应该怎么配置?
我使用AAAA*BBBB不行啊,我用的是C++的类库(一个正则表达式的类)
请各位高手给予指正?
谢谢了


主程序
        #include <stdio.h>
#include <string>
#include <iostream>

#include "regexpr.hpp"


using namespace std;
       
int main()
{

        archy::reg_expr* reg = new archy::reg_expr("IC = FALSE.*OC = FALSE";
               
        string str = "IC = FALSE\r\n                            OC = FALSE";
       
        cout<<reg->match(str)<<endl;

        return 0;
}


类的.h文件
#if !defined(RCOBJECT_RCIPTR)
#define RCOBJECT_RCIPTR

namespace archy {
       
class rcobject {                       // base class for reference-
public:                                // counted objects
        void addReference(){ ++refCount; }
        void removeReference(){ if (--refCount == 0)         delete this; }
       
        void markUnshareable(){ shareable = false; }
        bool isShareable() const{ return shareable; }
       
        bool isShared() const{ return refCount > 1; }

protected:
        rcobject()
        :refCount(0), shareable(true)
        {}
        rcobject(const rcobject& rhs)
        :refCount(0), shareable(true)
        {}
        rcobject& operator=(const rcobject& rhs)
        { return *this; }
        virtual ~rcobject(){}

private:
        int refCount;
        bool shareable;
};


template<class T>
class rcptr {
public:
        rcptr(T* realPtr = 0);
        rcptr(const rcptr& rhs);
        ~rcptr();
       
        rcptr& operator=(const rcptr& rhs);
       
        const T* operator->() const;               // see below for an
        T* operator->();                           // explanation of why
        const T& operator*() const;                // these functions are
        T& operator*();                            // declared this way
       
       
        operator const T* () const { return counter->pointee; }
        operator T*() {
                return counter->pointee;
        }
    operator bool () const {
                return counter->pointee != 0;
    }
       
private:
        struct CountHolder: public rcobject {
                ~CountHolder() { delete pointee; }
                T *pointee;
        };
       
        CountHolder *counter;
       
        void init();
        void makeCopy();                           // see below
};

template<class T>
void rcptr<T>::init()
{
        if (counter->isShareable() == false) {
                T *oldValue = counter->pointee;
                counter = new CountHolder;
                counter->pointee = new T(*oldValue);
        }
       
        counter->addReference();
}

template<class T>
rcptr<T>::rcptr(T* realPtr)
:counter(new CountHolder)
{
        counter->pointee = realPtr;
        init();
}

template<class T>
rcptr<T>::rcptr(const rcptr& rhs)
:counter(rhs.counter)
{ init(); }

template<class T>
rcptr<T>::~rcptr()
{ counter->removeReference(); }

template<class T>
rcptr<T>& rcptr<T>:perator=(const rcptr& rhs)
{
        if (counter != rhs.counter) {
                counter->removeReference();
                counter = rhs.counter;
                init();
        }
        return *this;
}

template<class T>                          // implement the copy
void rcptr<T>::makeCopy()                 // part of copy-on-
{                                          // write (COW)
        if (counter->isShared()) {
                T *oldValue = counter->pointee;
                counter->removeReference();
                counter = new CountHolder;
                counter->pointee = new T(*oldValue);
                counter->addReference();
        }
}

template<class T>                           // const access;
const T* rcptr<T>:perator->() const      // no COW needed
{ return counter->pointee; }

template<class T>                           // non-const
T* rcptr<T>:perator->()                  // access; COW
{ makeCopy(); return counter->pointee; }    // needed

template<class T>                           // const access;
const T& rcptr<T>:perator*() const       // no COW needed
{ return *(counter->pointee); }

template<class T>                           // non-const
T& rcptr<T>:perator*()                   // access; do the
{ makeCopy(); return *(counter->pointee); } // COW thing


} // namespace archy

#endif


类的cpp文件
#include "regexpr.hpp"

#include "pcre.h"

namespace archy {

reg_expr::reg_expr()
: m_NumFound(0)
, m_PReg(0)
{
}

string reg_expr::get_replacedstring(const string& strSrc)
{
        const char *src = strSrc.c_str();
        char c;
        int no;


        // First compute the length of the string
        int replacelen = 0;
        while ((c = *src++) != '\0') {
                if (c == '&')
                        no = 0;
                else if (c == '\\' && isdigit(*src))
                        no = *src++ - '0';
                else
                        no = -1;

                if (no < 0) {       
                        // Ordinary character.
                        if (c == '\\' && (*src == '\\' || *src == '&' ) )
                                c = *src++;
                        replacelen++;
                }
                else if ( no <= count() ) {
                        // Get tagged expression
                        replacelen += sub_len(no);
                }
        }
               
        char* buf = new char[ replacelen + 1 ];
        char* tmp = buf;
        memset(buf, 0 , replacelen + 1);
        // Now we can create the string
        src = strSrc.c_str();
        while ((c = *src++) != '\0') {
                if (c == '&')
                        no = 0;
                else if (c == '\\' && isdigit(*src))
                        no = *src++ - ('0');
                else
                        no = -1;

                if (no < 0) {       
                        // Ordinary character.
                        if (c == '\\' && (*src == '\\' || *src == '&'))
                                c = *src++;
                        *buf++ = c;
                }
                else if ( no <= count() ) {
                        // Get tagged expression
                        int len = sub_len(no);
                        strncpy(buf, m_strSrc.c_str() + sub_start(no), len);
                        buf[len] = 0;
                        buf += len;
                        if (len != 0 && *(buf-1) ==  '\0' ) {       
                                /* strncpy hit NUL. */
                                fprintf(stderr, "damaged match string\n";
                                delete []tmp;
                                return "";
                        }
                }
        }
        printf("temp:%s\n", tmp);
        string szReplace(tmp);
        delete []tmp;
        return szReplace;
}
reg_expr::reg_expr(const string &pat, TCompile flags) throw (runtime_error)
: m_NumFound(0)
{
    const char *error;
    int erroffset;
    m_PReg = pcre_compile(pat.c_str(), flags, &error, &erroffset, NULL);
    if (m_PReg == NULL) {
        throw runtime_error(error);
    }
}


reg_expr::~reg_expr()
{
    (*pcre_free)((pcre*)m_PReg);
}


void reg_expr::set(const string &pat, TCompile flags)throw (runtime_error)
{
    if (m_PReg != NULL) {
        (*pcre_free)((pcre*)m_PReg);
    }

    const char *error;
    int erroffset;
    m_PReg = pcre_compile(pat.c_str(), flags, &error, &erroffset, NULL);
    if (m_PReg == NULL) {
        throw runtime_error(error);
    }
}

string reg_expr:perator[]( int i ) const
{
    if ( i >= m_NumFound){
        return "";
    }
    size_t len = m_Results[2 * i + 1] - m_Results[2 * i];
    return m_strSrc.substr(m_Results[2 * i], len);
}

// Return the starting offset of the ith matched substring from the
// beginning of the string used in match().
int reg_expr::sub_start( int i ) const
{
        return m_Results[2 * i];
}

       
// Return the length of the ith matched substring
int reg_expr::sub_len( int i ) const
{
        return m_Results[2 * i + 1] - m_Results[2 * i];
}

bool reg_expr::match(const string& str, TMatch flags)
{
    m_NumFound = pcre_exec((pcre*)m_PReg, NULL, str.c_str(),  str.length(), 0,
        flags, m_Results, (kRegexpMaxSubPatterns +1) * 3);
    if (m_NumFound <= 0) {
        return false;
    } else {
            m_strSrc = str;
        return true;
    }
}


int reg_expr::count() const
{
    return m_NumFound;
}



}

论坛徽章:
0
2 [报告]
发表于 2006-06-20 08:51 |只看该作者

c的正则表达式函数只有几个

表达式上加个括号试试看,(AAAA)*(BBBB)

论坛徽章:
0
3 [报告]
发表于 2006-06-20 12:39 |只看该作者
原帖由 wuleisky 于 2006-6-19 19:54 发表


现在要匹配这样一个字符串
AAAA   ddddddd   回车
12345  回车
BBBB   回车
我要从中匹配是否存在AAAA,而且也存在BBBB,应该怎么配置?
我使用AAAA*BBBB不行啊,我用的是C++的类库(一个正则表达式的 ...


试试 AAAA.*BBBB
你看看那个库里面匹配的时候,有没有多行匹配的选项?有的库里面,默认.是不匹配换行符号的。
可以实验一下手工加上换行试试能否匹配到
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP