]>
git.saurik.com Git - wxWidgets.git/blob - src/common/regex.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/regex.cpp
3 // Purpose: regular expression matching
4 // Author: Karsten Ballüder and Vadim Zeitlin
8 // Copyright: (c) 2000 Karsten Ballüder <ballueder@gmx.net>
9 // 2001 Vadim Zeitlin <vadim@wxwindows.org>
10 // Licence: wxWindows licence
11 ///////////////////////////////////////////////////////////////////////////////
13 // ============================================================================
15 // ============================================================================
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
31 #include "wx/object.h"
32 #include "wx/string.h"
37 // FreeBSD, Watcom and DMars require this, CW doesn't have nor need it.
38 // Others also don't seem to need it. If you have an error related to
39 // (not) including <sys/types.h> please report details to
40 // wx-dev@lists.wxwindows.org
41 #if defined(__UNIX__) || defined(__WATCOMC__) || defined(__DIGITALMARS__)
42 # include <sys/types.h>
48 // WXREGEX_USING_BUILTIN defined when using the built-in regex lib
49 // WXREGEX_USING_RE_SEARCH defined when using re_search in the GNU regex lib
50 // WXREGEX_IF_NEED_LEN() wrap the len parameter only used with the built-in
52 // WXREGEX_CONVERT_TO_MB defined when the regex lib is using chars and
53 // wxChar is wide, so conversion must be done
54 // WXREGEX_CHAR(x) Convert wxChar to wxRegChar
57 # define WXREGEX_USING_BUILTIN
58 # define WXREGEX_IF_NEED_LEN(x) ,x
60 # define WXREGEX_CHAR(x) x.wc_str()
62 # define WXREGEX_CHAR(x) x.mb_str()
65 # ifdef HAVE_RE_SEARCH
66 # define WXREGEX_IF_NEED_LEN(x) ,x
67 # define WXREGEX_USING_RE_SEARCH
69 # define WXREGEX_IF_NEED_LEN(x)
72 # define WXREGEX_CONVERT_TO_MB
74 # define WXREGEX_CHAR(x) x.mb_str()
75 # define wx_regfree regfree
76 # define wx_regerror regerror
79 // ----------------------------------------------------------------------------
81 // ----------------------------------------------------------------------------
83 #ifndef WXREGEX_USING_RE_SEARCH
85 // the array of offsets for the matches, the usual POSIX regmatch_t array.
89 typedef regmatch_t
*match_type
;
91 wxRegExMatches(size_t n
) { m_matches
= new regmatch_t
[n
]; }
92 ~wxRegExMatches() { delete [] m_matches
; }
94 // we just use casts here because the fields of regmatch_t struct may be 64
95 // bit but we're limited to size_t in our public API and are not going to
96 // change it because operating on strings longer than 4GB using it is
97 // absolutely impractical anyhow
98 size_t Start(size_t n
) const
100 return wx_truncate_cast(size_t, m_matches
[n
].rm_so
);
103 size_t End(size_t n
) const
105 return wx_truncate_cast(size_t, m_matches
[n
].rm_eo
);
108 regmatch_t
*get() const { return m_matches
; }
111 regmatch_t
*m_matches
;
114 #else // WXREGEX_USING_RE_SEARCH
116 // the array of offsets for the matches, the struct used by the GNU lib
120 typedef re_registers
*match_type
;
122 wxRegExMatches(size_t n
)
124 m_matches
.num_regs
= n
;
125 m_matches
.start
= new regoff_t
[n
];
126 m_matches
.end
= new regoff_t
[n
];
131 delete [] m_matches
.start
;
132 delete [] m_matches
.end
;
135 size_t Start(size_t n
) const { return m_matches
.start
[n
]; }
136 size_t End(size_t n
) const { return m_matches
.end
[n
]; }
138 re_registers
*get() { return &m_matches
; }
141 re_registers m_matches
;
144 #endif // WXREGEX_USING_RE_SEARCH
146 // the character type used by the regular expression engine
147 #ifndef WXREGEX_CONVERT_TO_MB
148 typedef wxChar wxRegChar
;
150 typedef char wxRegChar
;
153 // the real implementation of wxRegEx
161 // return true if Compile() had been called successfully
162 bool IsValid() const { return m_isCompiled
; }
165 bool Compile(const wxString
& expr
, int flags
= 0);
166 bool Matches(const wxRegChar
*str
, int flags
167 WXREGEX_IF_NEED_LEN(size_t len
)) const;
168 bool GetMatch(size_t *start
, size_t *len
, size_t index
= 0) const;
169 size_t GetMatchCount() const;
170 int Replace(wxString
*pattern
, const wxString
& replacement
,
171 size_t maxMatches
= 0) const;
174 // return the string containing the error message for the given err code
175 wxString
GetErrorMsg(int errorcode
, bool badconv
) const;
180 m_isCompiled
= false;
185 // free the RE if compiled
190 wx_regfree(&m_RegEx
);
196 // free the RE if any and reinit the members
206 // the subexpressions data
207 wxRegExMatches
*m_Matches
;
210 // true if m_RegEx is valid
215 // ============================================================================
217 // ============================================================================
219 // ----------------------------------------------------------------------------
221 // ----------------------------------------------------------------------------
223 wxRegExImpl::wxRegExImpl()
228 wxRegExImpl::~wxRegExImpl()
233 wxString
wxRegExImpl::GetErrorMsg(int errorcode
, bool badconv
) const
235 #ifdef WXREGEX_CONVERT_TO_MB
236 // currently only needed when using system library in Unicode mode
239 return _("conversion to 8-bit encoding failed");
242 // 'use' badconv to avoid a compiler warning
248 // first get the string length needed
249 int len
= wx_regerror(errorcode
, &m_RegEx
, NULL
, 0);
252 char* szcmbError
= new char[++len
];
254 (void)wx_regerror(errorcode
, &m_RegEx
, szcmbError
, len
);
256 szError
= wxConvLibc
.cMB2WX(szcmbError
);
257 delete [] szcmbError
;
259 else // regerror() returned 0
261 szError
= _("unknown error");
267 bool wxRegExImpl::Compile(const wxString
& expr
, int flags
)
271 #ifdef WX_NO_REGEX_ADVANCED
272 # define FLAVORS wxRE_BASIC
274 # define FLAVORS (wxRE_ADVANCED | wxRE_BASIC)
275 wxASSERT_MSG( (flags
& FLAVORS
) != FLAVORS
,
276 _T("incompatible flags in wxRegEx::Compile") );
278 wxASSERT_MSG( !(flags
& ~(FLAVORS
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
279 _T("unrecognized flags in wxRegEx::Compile") );
281 // translate our flags to regcomp() ones
283 if ( !(flags
& wxRE_BASIC
) )
284 #ifndef WX_NO_REGEX_ADVANCED
285 if (flags
& wxRE_ADVANCED
)
286 flagsRE
|= REG_ADVANCED
;
289 flagsRE
|= REG_EXTENDED
;
290 if ( flags
& wxRE_ICASE
)
291 flagsRE
|= REG_ICASE
;
292 if ( flags
& wxRE_NOSUB
)
293 flagsRE
|= REG_NOSUB
;
294 if ( flags
& wxRE_NEWLINE
)
295 flagsRE
|= REG_NEWLINE
;
298 #ifdef WXREGEX_USING_BUILTIN
300 // FIXME-UTF8: use wc_str() after removing ANSI build
301 int errorcode
= wx_re_comp(&m_RegEx
, expr
.c_str(), expr
.length(), flagsRE
);
303 // FIXME-UTF8: this is potentially broken, we shouldn't even try it
304 // and should always use builtin regex library (or PCRE?)
305 const wxWX2MBbuf conv
= expr
.mbc_str();
306 int errorcode
= conv
? regcomp(&m_RegEx
, conv
, flagsRE
) : REG_BADPAT
;
311 wxLogError(_("Invalid regular expression '%s': %s"),
312 expr
.c_str(), GetErrorMsg(errorcode
, !conv
).c_str());
314 m_isCompiled
= false;
318 // don't allocate the matches array now, but do it later if necessary
319 if ( flags
& wxRE_NOSUB
)
321 // we don't need it at all
326 // we will alloc the array later (only if really needed) but count
327 // the number of sub-expressions in the regex right now
329 // there is always one for the whole expression
332 // and some more for bracketed subexperessions
333 for ( const wxChar
*cptr
= expr
.c_str(); *cptr
; cptr
++ )
335 if ( *cptr
== _T('\\') )
337 // in basic RE syntax groups are inside \(...\)
338 if ( *++cptr
== _T('(') && (flags
& wxRE_BASIC
) )
343 else if ( *cptr
== _T('(') && !(flags
& wxRE_BASIC
) )
345 // we know that the previous character is not an unquoted
346 // backslash because it would have been eaten above, so we
347 // have a bare '(' and this indicates a group start for the
348 // extended syntax. '(?' is used for extensions by perl-
349 // like REs (e.g. advanced), and is not valid for POSIX
350 // extended, so ignore them always.
351 if ( cptr
[1] != _T('?') )
363 #ifdef WXREGEX_USING_RE_SEARCH
365 // On GNU, regexec is implemented as a wrapper around re_search. re_search
366 // requires a length parameter which the POSIX regexec does not have,
367 // therefore regexec must do a strlen on the search text each time it is
368 // called. This can drastically affect performance when matching is done in
369 // a loop along a string, such as during a search and replace. Therefore if
370 // re_search is detected by configure, it is used directly.
372 static int ReSearch(const regex_t
*preg
,
375 re_registers
*matches
,
378 regex_t
*pattern
= wx_const_cast(regex_t
*, preg
);
380 pattern
->not_bol
= (eflags
& REG_NOTBOL
) != 0;
381 pattern
->not_eol
= (eflags
& REG_NOTEOL
) != 0;
382 pattern
->regs_allocated
= REGS_FIXED
;
384 int ret
= re_search(pattern
, text
, len
, 0, len
, matches
);
385 return ret
>= 0 ? 0 : REG_NOMATCH
;
388 #endif // WXREGEX_USING_RE_SEARCH
390 bool wxRegExImpl::Matches(const wxRegChar
*str
,
392 WXREGEX_IF_NEED_LEN(size_t len
)) const
394 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
396 // translate our flags to regexec() ones
397 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
398 _T("unrecognized flags in wxRegEx::Matches") );
401 if ( flags
& wxRE_NOTBOL
)
402 flagsRE
|= REG_NOTBOL
;
403 if ( flags
& wxRE_NOTEOL
)
404 flagsRE
|= REG_NOTEOL
;
406 // allocate matches array if needed
407 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
408 if ( !m_Matches
&& m_nMatches
)
410 self
->m_Matches
= new wxRegExMatches(m_nMatches
);
413 wxRegExMatches::match_type matches
= m_Matches
? m_Matches
->get() : NULL
;
416 #if defined WXREGEX_USING_BUILTIN
417 int rc
= wx_re_exec(&self
->m_RegEx
, str
, len
, NULL
, m_nMatches
, matches
, flagsRE
);
418 #elif defined WXREGEX_USING_RE_SEARCH
419 int rc
= str
? ReSearch(&self
->m_RegEx
, str
, len
, matches
, flagsRE
) : REG_BADPAT
;
421 int rc
= str
? regexec(&self
->m_RegEx
, str
, m_nMatches
, matches
, flagsRE
) : REG_BADPAT
;
427 // matched successfully
432 wxLogError(_("Failed to find match for regular expression: %s"),
433 GetErrorMsg(rc
, !str
).c_str());
442 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
444 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
445 wxCHECK_MSG( m_nMatches
, false, _T("can't use with wxRE_NOSUB") );
446 wxCHECK_MSG( m_Matches
, false, _T("must call Matches() first") );
447 wxCHECK_MSG( index
< m_nMatches
, false, _T("invalid match index") );
450 *start
= m_Matches
->Start(index
);
452 *len
= m_Matches
->End(index
) - m_Matches
->Start(index
);
457 size_t wxRegExImpl::GetMatchCount() const
459 wxCHECK_MSG( IsValid(), 0, _T("must successfully Compile() first") );
460 wxCHECK_MSG( m_nMatches
, 0, _T("can't use with wxRE_NOSUB") );
465 int wxRegExImpl::Replace(wxString
*text
,
466 const wxString
& replacement
,
467 size_t maxMatches
) const
469 wxCHECK_MSG( text
, wxNOT_FOUND
, _T("NULL text in wxRegEx::Replace") );
470 wxCHECK_MSG( IsValid(), wxNOT_FOUND
, _T("must successfully Compile() first") );
473 #ifndef WXREGEX_CONVERT_TO_MB
474 const wxChar
*textstr
= text
->c_str();
475 size_t textlen
= text
->length();
477 const wxWX2MBbuf textstr
= WXREGEX_CHAR(*text
);
480 wxLogError(_("Failed to find match for regular expression: %s"),
481 GetErrorMsg(0, true).c_str());
484 size_t textlen
= strlen(textstr
);
488 // the replacement text
491 // the result, allow 25% extra
493 result
.reserve(5 * textlen
/ 4);
495 // attempt at optimization: don't iterate over the string if it doesn't
496 // contain back references at all
497 bool mayHaveBackrefs
=
498 replacement
.find_first_of(_T("\\&")) != wxString::npos
;
500 if ( !mayHaveBackrefs
)
502 textNew
= replacement
;
505 // the position where we start looking for the match
506 size_t matchStart
= 0;
508 // number of replacement made: we won't make more than maxMatches of them
509 // (unless maxMatches is 0 which doesn't limit the number of replacements)
510 size_t countRepl
= 0;
512 // note that "^" shouldn't match after the first call to Matches() so we
513 // use wxRE_NOTBOL to prevent it from happening
514 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
515 Matches(textstr
+ matchStart
,
516 countRepl
? wxRE_NOTBOL
: 0
517 WXREGEX_IF_NEED_LEN(textlen
- matchStart
)) )
519 // the string possibly contains back references: we need to calculate
520 // the replacement text anew after each match
521 if ( mayHaveBackrefs
)
523 mayHaveBackrefs
= false;
525 textNew
.reserve(replacement
.length());
527 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
529 size_t index
= (size_t)-1;
531 if ( *p
== _T('\\') )
533 if ( wxIsdigit(*++p
) )
537 index
= (size_t)wxStrtoul(p
, &end
, 10);
538 p
= end
- 1; // -1 to compensate for p++ in the loop
540 //else: backslash used as escape character
542 else if ( *p
== _T('&') )
544 // treat this as "\0" for compatbility with ed and such
548 // do we have a back reference?
549 if ( index
!= (size_t)-1 )
553 if ( !GetMatch(&start
, &len
, index
) )
555 wxFAIL_MSG( _T("invalid back reference") );
561 textNew
+= wxString(textstr
+ matchStart
+ start
,
562 *wxConvCurrent
, len
);
564 mayHaveBackrefs
= true;
567 else // ordinary character
575 if ( !GetMatch(&start
, &len
) )
577 // we did have match as Matches() returned true above!
578 wxFAIL_MSG( _T("internal logic error in wxRegEx::Replace") );
583 // an insurance against implementations that don't grow exponentially
584 // to ensure building the result takes linear time
585 if (result
.capacity() < result
.length() + start
+ textNew
.length())
586 result
.reserve(2 * result
.length());
588 #ifndef WXREGEX_CONVERT_TO_MB
589 result
.append(*text
, matchStart
, start
);
591 result
.append(wxString(textstr
+ matchStart
, *wxConvCurrent
, start
));
594 result
.append(textNew
);
601 #ifndef WXREGEX_CONVERT_TO_MB
602 result
.append(*text
, matchStart
, wxString::npos
);
604 result
.append(wxString(textstr
+ matchStart
, *wxConvCurrent
));
611 // ----------------------------------------------------------------------------
612 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
613 // ----------------------------------------------------------------------------
625 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
629 m_impl
= new wxRegExImpl
;
632 if ( !m_impl
->Compile(expr
, flags
) )
634 // error message already given in wxRegExImpl::Compile
644 bool wxRegEx::Matches(const wxString
& str
, int flags
) const
646 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
648 return m_impl
->Matches(WXREGEX_CHAR(str
), flags
649 WXREGEX_IF_NEED_LEN(str
.length()));
652 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
654 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
656 return m_impl
->GetMatch(start
, len
, index
);
659 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
662 if ( !GetMatch(&start
, &len
, index
) )
663 return wxEmptyString
;
665 return text
.Mid(start
, len
);
668 size_t wxRegEx::GetMatchCount() const
670 wxCHECK_MSG( IsValid(), 0, _T("must successfully Compile() first") );
672 return m_impl
->GetMatchCount();
675 int wxRegEx::Replace(wxString
*pattern
,
676 const wxString
& replacement
,
677 size_t maxMatches
) const
679 wxCHECK_MSG( IsValid(), wxNOT_FOUND
, _T("must successfully Compile() first") );
681 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
684 #endif // wxUSE_REGEX