regex.cpp

来自「A*算法 A*算法 A*算法 A*算法A*算法A*算法」· C++ 代码 · 共 691 行 · 第 1/2 页

CPP
691
字号
///////////////////////////////////////////////////////////////////////////////
// Name:        src/common/regex.cpp
// Purpose:     regular expression matching
// Author:      Karsten Ball黡er and Vadim Zeitlin
// Modified by:
// Created:     13.07.01
// RCS-ID:      $Id: regex.cpp,v 1.35.2.2 2005/11/27 18:12:37 MW Exp $
// Copyright:   (c) 2000 Karsten Ball黡er <ballueder@gmx.net>
//                  2001 Vadim Zeitlin <vadim@wxwindows.org>
// Licence:     wxWindows licence
///////////////////////////////////////////////////////////////////////////////

// ============================================================================
// declarations
// ============================================================================

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------

#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
    #pragma implementation "regex.h"
#endif

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_REGEX

#ifndef WX_PRECOMP
    #include "wx/object.h"
    #include "wx/string.h"
    #include "wx/log.h"
    #include "wx/intl.h"
#endif //WX_PRECOMP

// FreeBSD, Watcom and DMars require this, CW doesn't have nor need it.
// Others also don't seem to need it. If you have an error related to
// (not) including <sys/types.h> please report details to
// wx-dev@lists.wxwindows.org
#if defined(__UNIX__) || defined(__WATCOMC__) || defined(__DIGITALMARS__)
#   include <sys/types.h>
#endif

#include <regex.h>
#include "wx/regex.h"

// WXREGEX_USING_BUILTIN    defined when using the built-in regex lib
// WXREGEX_USING_RE_SEARCH  defined when using re_search in the GNU regex lib
// WXREGEX_IF_NEED_LEN()    wrap the len parameter only used with the built-in
//                          or GNU regex
// WXREGEX_CONVERT_TO_MB    defined when the regex lib is using chars and
//                          wxChar is wide, so conversion must be done
// WXREGEX_CHAR(x)          Convert wxChar to wxRegChar
//
#ifdef __REG_NOFRONT
#   define WXREGEX_USING_BUILTIN
#   define WXREGEX_IF_NEED_LEN(x) ,x
#   define WXREGEX_CHAR(x) x
#else
#   ifdef HAVE_RE_SEARCH
#       define WXREGEX_IF_NEED_LEN(x) ,x
#       define WXREGEX_USING_RE_SEARCH
#   else
#       define WXREGEX_IF_NEED_LEN(x)
#   endif
#   if wxUSE_UNICODE
#       define WXREGEX_CONVERT_TO_MB
#   endif
#   define WXREGEX_CHAR(x) wxConvertWX2MB(x)
#   define wx_regfree regfree
#   define wx_regerror regerror
#endif

// ----------------------------------------------------------------------------
// private classes
// ----------------------------------------------------------------------------

#ifndef WXREGEX_USING_RE_SEARCH

// the array of offsets for the matches, the usual POSIX regmatch_t array.
class wxRegExMatches
{
public:
    typedef regmatch_t *match_type;

    wxRegExMatches(size_t n)        { m_matches = new regmatch_t[n]; }
    ~wxRegExMatches()               { delete [] m_matches; }

    // we just use casts here because the fields of regmatch_t struct may be 64
    // bit but we're limited to size_t in our public API and are not going to
    // change it because operating on strings longer than 4GB using it is
    // absolutely impractical anyhow, but still check at least in debug
    size_t Start(size_t n) const
    {
        return wx_truncate_cast(size_t, m_matches[n].rm_so);
    }

    size_t End(size_t n) const
    {
        return wx_truncate_cast(size_t, m_matches[n].rm_eo);
    }

    regmatch_t *get() const         { return m_matches; }

private:
    regmatch_t *m_matches;
};

#else // WXREGEX_USING_RE_SEARCH

// the array of offsets for the matches, the struct used by the GNU lib
class wxRegExMatches
{
public:
    typedef re_registers *match_type;

    wxRegExMatches(size_t n)
    {
        m_matches.num_regs = n;
        m_matches.start = new regoff_t[n];
        m_matches.end = new regoff_t[n];
    }

    ~wxRegExMatches()
    {
        delete [] m_matches.start;
        delete [] m_matches.end;
    }

    size_t Start(size_t n) const    { return m_matches.start[n]; }
    size_t End(size_t n) const      { return m_matches.end[n]; }

    re_registers *get()             { return &m_matches; }

private:
    re_registers m_matches;
};

#endif // WXREGEX_USING_RE_SEARCH

// the character type used by the regular expression engine
#ifndef WXREGEX_CONVERT_TO_MB
typedef wxChar wxRegChar;
#else
typedef char wxRegChar;
#endif

// the real implementation of wxRegEx
class wxRegExImpl
{
public:
    // ctor and dtor
    wxRegExImpl();
    ~wxRegExImpl();

    // return true if Compile() had been called successfully
    bool IsValid() const { return m_isCompiled; }

    // RE operations
    bool Compile(const wxString& expr, int flags = 0);
    bool Matches(const wxRegChar *str, int flags
                 WXREGEX_IF_NEED_LEN(size_t len)) const;
    bool GetMatch(size_t *start, size_t *len, size_t index = 0) const;
    size_t GetMatchCount() const;
    int Replace(wxString *pattern, const wxString& replacement,
                size_t maxMatches = 0) const;

private:
    // return the string containing the error message for the given err code
    wxString GetErrorMsg(int errorcode, bool badconv = false) const;

    // init the members
    void Init()
    {
        m_isCompiled = false;
        m_Matches = NULL;
        m_nMatches = 0;
    }

    // free the RE if compiled
    void Free()
    {
        if ( IsValid() )
        {
            wx_regfree(&m_RegEx);
        }

        delete m_Matches;
    }

    // free the RE if any and reinit the members
    void Reinit()
    {
        Free();
        Init();
    }

    // compiled RE
    regex_t         m_RegEx;

    // the subexpressions data
    wxRegExMatches *m_Matches;
    size_t          m_nMatches;

    // true if m_RegEx is valid
    bool            m_isCompiled;
};


// ============================================================================
// implementation
// ============================================================================

// ----------------------------------------------------------------------------
// wxRegExImpl
// ----------------------------------------------------------------------------

wxRegExImpl::wxRegExImpl()
{
    Init();
}

wxRegExImpl::~wxRegExImpl()
{
    Free();
}

wxString wxRegExImpl::GetErrorMsg(int errorcode, bool badconv) const
{
#ifdef WXREGEX_CONVERT_TO_MB
    // currently only needed when using system library in Unicode mode
    if ( badconv )
    {
        return _("conversion to 8-bit encoding failed");
    }
#else
    // 'use' badconv to avoid a compiler warning
    (void)badconv;
#endif

    wxString szError;

    // first get the string length needed
    int len = wx_regerror(errorcode, &m_RegEx, NULL, 0);
    if ( len > 0 )
    {
        char* szcmbError = new char[++len];

        (void)wx_regerror(errorcode, &m_RegEx, szcmbError, len);

        szError = wxConvertMB2WX(szcmbError);
        delete [] szcmbError;
    }
    else // regerror() returned 0
    {
        szError = _("unknown error");
    }

    return szError;
}

bool wxRegExImpl::Compile(const wxString& expr, int flags)
{
    Reinit();

#ifdef WX_NO_REGEX_ADVANCED
#   define FLAVORS wxRE_BASIC
#else
#   define FLAVORS (wxRE_ADVANCED | wxRE_BASIC)
    wxASSERT_MSG( (flags & FLAVORS) != FLAVORS,
                  _T("incompatible flags in wxRegEx::Compile") );
#endif
    wxASSERT_MSG( !(flags & ~(FLAVORS | wxRE_ICASE | wxRE_NOSUB | wxRE_NEWLINE)),
                  _T("unrecognized flags in wxRegEx::Compile") );

    // translate our flags to regcomp() ones
    int flagsRE = 0;
    if ( !(flags & wxRE_BASIC) )
#ifndef WX_NO_REGEX_ADVANCED
        if (flags & wxRE_ADVANCED)
            flagsRE |= REG_ADVANCED;
        else
#endif
            flagsRE |= REG_EXTENDED;
    if ( flags & wxRE_ICASE )
        flagsRE |= REG_ICASE;
    if ( flags & wxRE_NOSUB )
        flagsRE |= REG_NOSUB;
    if ( flags & wxRE_NEWLINE )
        flagsRE |= REG_NEWLINE;

    // compile it
#ifdef WXREGEX_USING_BUILTIN
    bool conv = true;
    int errorcode = wx_re_comp(&m_RegEx, expr, expr.length(), flagsRE);
#else
    const wxWX2MBbuf conv = expr.mbc_str();
    int errorcode = conv ? regcomp(&m_RegEx, conv, flagsRE) : REG_BADPAT;
#endif

    if ( errorcode )
    {
        wxLogError(_("Invalid regular expression '%s': %s"),
                   expr.c_str(), GetErrorMsg(errorcode, !conv).c_str());

        m_isCompiled = false;
    }
    else // ok
    {
        // don't allocate the matches array now, but do it later if necessary
        if ( flags & wxRE_NOSUB )
        {
            // we don't need it at all
            m_nMatches = 0;
        }
        else
        {
            // we will alloc the array later (only if really needed) but count
            // the number of sub-expressions in the regex right now

            // there is always one for the whole expression
            m_nMatches = 1;

            // and some more for bracketed subexperessions
            for ( const wxChar *cptr = expr.c_str(); *cptr; cptr++ )
            {
                if ( *cptr == _T('\\') )
                {
                    // in basic RE syntax groups are inside \(...\)
                    if ( *++cptr == _T('(') && (flags & wxRE_BASIC) )
                    {
                        m_nMatches++;
                    }
                }
                else if ( *cptr == _T('(') && !(flags & wxRE_BASIC) )
                {
                    // we know that the previous character is not an unquoted
                    // backslash because it would have been eaten above, so we
                    // have a bare '(' and this indicates a group start for the
                    // extended syntax. '(?' is used for extensions by perl-
                    // like REs (e.g. advanced), and is not valid for POSIX

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?