]>
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 Ballueder and Vadim Zeitlin
7 // Copyright: (c) 2000 Karsten Ballueder <ballueder@gmx.net>
8 // 2001 Vadim Zeitlin <vadim@wxwindows.org>
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
32 #include "wx/object.h"
38 // FreeBSD, Watcom and DMars require this, CW doesn't have nor need it.
39 // Others also don't seem to need it. If you have an error related to
40 // (not) including <sys/types.h> please report details to
41 // wx-dev@lists.wxwindows.org
42 #if defined(__UNIX__) || defined(__WATCOMC__) || defined(__DIGITALMARS__)
43 # 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 wxT("incompatible flags in wxRegEx::Compile") );
278 wxASSERT_MSG( !(flags
& ~(FLAVORS
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
279 wxT("unrecognized flags in wxRegEx::Compile") );
281 // translate our flags to regcomp() ones
283 if ( !(flags
& wxRE_BASIC
) )
285 #ifndef WX_NO_REGEX_ADVANCED
286 if (flags
& wxRE_ADVANCED
)
287 flagsRE
|= REG_ADVANCED
;
290 flagsRE
|= REG_EXTENDED
;
292 if ( flags
& wxRE_ICASE
)
293 flagsRE
|= REG_ICASE
;
294 if ( flags
& wxRE_NOSUB
)
295 flagsRE
|= REG_NOSUB
;
296 if ( flags
& wxRE_NEWLINE
)
297 flagsRE
|= REG_NEWLINE
;
300 #ifdef WXREGEX_USING_BUILTIN
302 // FIXME-UTF8: use wc_str() after removing ANSI build
303 int errorcode
= wx_re_comp(&m_RegEx
, expr
.c_str(), expr
.length(), flagsRE
);
305 // FIXME-UTF8: this is potentially broken, we shouldn't even try it
306 // and should always use builtin regex library (or PCRE?)
307 const wxWX2MBbuf conv
= expr
.mbc_str();
308 int errorcode
= conv
? regcomp(&m_RegEx
, conv
, flagsRE
) : REG_BADPAT
;
313 wxLogError(_("Invalid regular expression '%s': %s"),
314 expr
.c_str(), GetErrorMsg(errorcode
, !conv
).c_str());
316 m_isCompiled
= false;
320 // don't allocate the matches array now, but do it later if necessary
321 if ( flags
& wxRE_NOSUB
)
323 // we don't need it at all
328 // we will alloc the array later (only if really needed) but count
329 // the number of sub-expressions in the regex right now
331 // there is always one for the whole expression
334 // and some more for bracketed subexperessions
335 for ( const wxChar
*cptr
= expr
.c_str(); *cptr
; cptr
++ )
337 if ( *cptr
== wxT('\\') )
339 // in basic RE syntax groups are inside \(...\)
340 if ( *++cptr
== wxT('(') && (flags
& wxRE_BASIC
) )
345 else if ( *cptr
== wxT('(') && !(flags
& wxRE_BASIC
) )
347 // we know that the previous character is not an unquoted
348 // backslash because it would have been eaten above, so we
349 // have a bare '(' and this indicates a group start for the
350 // extended syntax. '(?' is used for extensions by perl-
351 // like REs (e.g. advanced), and is not valid for POSIX
352 // extended, so ignore them always.
353 if ( cptr
[1] != wxT('?') )
365 #ifdef WXREGEX_USING_RE_SEARCH
367 // On GNU, regexec is implemented as a wrapper around re_search. re_search
368 // requires a length parameter which the POSIX regexec does not have,
369 // therefore regexec must do a strlen on the search text each time it is
370 // called. This can drastically affect performance when matching is done in
371 // a loop along a string, such as during a search and replace. Therefore if
372 // re_search is detected by configure, it is used directly.
374 static int ReSearch(const regex_t
*preg
,
377 re_registers
*matches
,
380 regex_t
*pattern
= const_cast<regex_t
*>(preg
);
382 pattern
->not_bol
= (eflags
& REG_NOTBOL
) != 0;
383 pattern
->not_eol
= (eflags
& REG_NOTEOL
) != 0;
384 pattern
->regs_allocated
= REGS_FIXED
;
386 int ret
= re_search(pattern
, text
, len
, 0, len
, matches
);
387 return ret
>= 0 ? 0 : REG_NOMATCH
;
390 #endif // WXREGEX_USING_RE_SEARCH
392 bool wxRegExImpl::Matches(const wxRegChar
*str
,
394 WXREGEX_IF_NEED_LEN(size_t len
)) const
396 wxCHECK_MSG( IsValid(), false, wxT("must successfully Compile() first") );
398 // translate our flags to regexec() ones
399 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
400 wxT("unrecognized flags in wxRegEx::Matches") );
403 if ( flags
& wxRE_NOTBOL
)
404 flagsRE
|= REG_NOTBOL
;
405 if ( flags
& wxRE_NOTEOL
)
406 flagsRE
|= REG_NOTEOL
;
408 // allocate matches array if needed
409 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
410 if ( !m_Matches
&& m_nMatches
)
412 self
->m_Matches
= new wxRegExMatches(m_nMatches
);
415 wxRegExMatches::match_type matches
= m_Matches
? m_Matches
->get() : NULL
;
418 #if defined WXREGEX_USING_BUILTIN
419 int rc
= wx_re_exec(&self
->m_RegEx
, str
, len
, NULL
, m_nMatches
, matches
, flagsRE
);
420 #elif defined WXREGEX_USING_RE_SEARCH
421 int rc
= str
? ReSearch(&self
->m_RegEx
, str
, len
, matches
, flagsRE
) : REG_BADPAT
;
423 int rc
= str
? regexec(&self
->m_RegEx
, str
, m_nMatches
, matches
, flagsRE
) : REG_BADPAT
;
429 // matched successfully
434 wxLogError(_("Failed to find match for regular expression: %s"),
435 GetErrorMsg(rc
, !str
).c_str());
444 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
446 wxCHECK_MSG( IsValid(), false, wxT("must successfully Compile() first") );
447 wxCHECK_MSG( m_nMatches
, false, wxT("can't use with wxRE_NOSUB") );
448 wxCHECK_MSG( m_Matches
, false, wxT("must call Matches() first") );
449 wxCHECK_MSG( index
< m_nMatches
, false, wxT("invalid match index") );
452 *start
= m_Matches
->Start(index
);
454 *len
= m_Matches
->End(index
) - m_Matches
->Start(index
);
459 size_t wxRegExImpl::GetMatchCount() const
461 wxCHECK_MSG( IsValid(), 0, wxT("must successfully Compile() first") );
462 wxCHECK_MSG( m_nMatches
, 0, wxT("can't use with wxRE_NOSUB") );
467 int wxRegExImpl::Replace(wxString
*text
,
468 const wxString
& replacement
,
469 size_t maxMatches
) const
471 wxCHECK_MSG( text
, wxNOT_FOUND
, wxT("NULL text in wxRegEx::Replace") );
472 wxCHECK_MSG( IsValid(), wxNOT_FOUND
, wxT("must successfully Compile() first") );
475 #ifndef WXREGEX_CONVERT_TO_MB
476 const wxChar
*textstr
= text
->c_str();
477 size_t textlen
= text
->length();
479 const wxWX2MBbuf textstr
= WXREGEX_CHAR(*text
);
482 wxLogError(_("Failed to find match for regular expression: %s"),
483 GetErrorMsg(0, true).c_str());
486 size_t textlen
= strlen(textstr
);
490 // the replacement text
493 // the result, allow 25% extra
495 result
.reserve(5 * textlen
/ 4);
497 // attempt at optimization: don't iterate over the string if it doesn't
498 // contain back references at all
499 bool mayHaveBackrefs
=
500 replacement
.find_first_of(wxT("\\&")) != wxString::npos
;
502 if ( !mayHaveBackrefs
)
504 textNew
= replacement
;
507 // the position where we start looking for the match
508 size_t matchStart
= 0;
510 // number of replacement made: we won't make more than maxMatches of them
511 // (unless maxMatches is 0 which doesn't limit the number of replacements)
512 size_t countRepl
= 0;
514 // note that "^" shouldn't match after the first call to Matches() so we
515 // use wxRE_NOTBOL to prevent it from happening
516 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
518 #ifndef WXREGEX_CONVERT_TO_MB
519 textstr
+ matchStart
,
521 textstr
.data() + matchStart
,
523 countRepl
? wxRE_NOTBOL
: 0
524 WXREGEX_IF_NEED_LEN(textlen
- matchStart
)) )
526 // the string possibly contains back references: we need to calculate
527 // the replacement text anew after each match
528 if ( mayHaveBackrefs
)
530 mayHaveBackrefs
= false;
532 textNew
.reserve(replacement
.length());
534 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
536 size_t index
= (size_t)-1;
538 if ( *p
== wxT('\\') )
540 if ( wxIsdigit(*++p
) )
544 index
= (size_t)wxStrtoul(p
, &end
, 10);
545 p
= end
- 1; // -1 to compensate for p++ in the loop
547 //else: backslash used as escape character
549 else if ( *p
== wxT('&') )
551 // treat this as "\0" for compatbility with ed and such
555 // do we have a back reference?
556 if ( index
!= (size_t)-1 )
560 if ( !GetMatch(&start
, &len
, index
) )
562 wxFAIL_MSG( wxT("invalid back reference") );
569 #ifndef WXREGEX_CONVERT_TO_MB
574 + matchStart
+ start
,
575 *wxConvCurrent
, len
);
577 mayHaveBackrefs
= true;
580 else // ordinary character
588 if ( !GetMatch(&start
, &len
) )
590 // we did have match as Matches() returned true above!
591 wxFAIL_MSG( wxT("internal logic error in wxRegEx::Replace") );
596 // an insurance against implementations that don't grow exponentially
597 // to ensure building the result takes linear time
598 if (result
.capacity() < result
.length() + start
+ textNew
.length())
599 result
.reserve(2 * result
.length());
601 #ifndef WXREGEX_CONVERT_TO_MB
602 result
.append(*text
, matchStart
, start
);
604 result
.append(wxString(textstr
.data() + matchStart
, *wxConvCurrent
, start
));
607 result
.append(textNew
);
614 #ifndef WXREGEX_CONVERT_TO_MB
615 result
.append(*text
, matchStart
, wxString::npos
);
617 result
.append(wxString(textstr
.data() + matchStart
, *wxConvCurrent
));
624 // ----------------------------------------------------------------------------
625 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
626 // ----------------------------------------------------------------------------
638 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
642 m_impl
= new wxRegExImpl
;
645 if ( !m_impl
->Compile(expr
, flags
) )
647 // error message already given in wxRegExImpl::Compile
656 bool wxRegEx::Matches(const wxString
& str
, int flags
) const
658 wxCHECK_MSG( IsValid(), false, wxT("must successfully Compile() first") );
660 return m_impl
->Matches(WXREGEX_CHAR(str
), flags
661 WXREGEX_IF_NEED_LEN(str
.length()));
664 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
666 wxCHECK_MSG( IsValid(), false, wxT("must successfully Compile() first") );
668 return m_impl
->GetMatch(start
, len
, index
);
671 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
674 if ( !GetMatch(&start
, &len
, index
) )
675 return wxEmptyString
;
677 return text
.Mid(start
, len
);
680 size_t wxRegEx::GetMatchCount() const
682 wxCHECK_MSG( IsValid(), 0, wxT("must successfully Compile() first") );
684 return m_impl
->GetMatchCount();
687 int wxRegEx::Replace(wxString
*pattern
,
688 const wxString
& replacement
,
689 size_t maxMatches
) const
691 wxCHECK_MSG( IsValid(), wxNOT_FOUND
, wxT("must successfully Compile() first") );
693 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
696 #endif // wxUSE_REGEX