]>
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
59 # define WXREGEX_CHAR(x) x
61 # ifdef HAVE_RE_SEARCH
62 # define WXREGEX_IF_NEED_LEN(x) ,x
63 # define WXREGEX_USING_RE_SEARCH
65 # define WXREGEX_IF_NEED_LEN(x)
68 # define WXREGEX_CONVERT_TO_MB
70 # define WXREGEX_CHAR(x) wxConvertWX2MB(x)
71 # define wx_regfree regfree
72 # define wx_regerror regerror
75 // ----------------------------------------------------------------------------
77 // ----------------------------------------------------------------------------
79 #ifndef WXREGEX_USING_RE_SEARCH
81 // the array of offsets for the matches, the usual POSIX regmatch_t array.
85 typedef regmatch_t
*match_type
;
87 wxRegExMatches(size_t n
) { m_matches
= new regmatch_t
[n
]; }
88 ~wxRegExMatches() { delete [] m_matches
; }
90 // we just use casts here because the fields of regmatch_t struct may be 64
91 // bit but we're limited to size_t in our public API and are not going to
92 // change it because operating on strings longer than 4GB using it is
93 // absolutely impractical anyhow, but still check at least in debug
94 size_t Start(size_t n
) const
96 wxASSERT_MSG( m_matches
[n
].rm_so
< UINT_MAX
, _T("regex offset overflow") );
97 return wx_truncate_cast(size_t, m_matches
[n
].rm_so
);
100 size_t End(size_t n
) const
102 wxASSERT_MSG( m_matches
[n
].rm_eo
< UINT_MAX
, _T("regex offset overflow") );
103 return wx_truncate_cast(size_t, m_matches
[n
].rm_eo
);
106 regmatch_t
*get() const { return m_matches
; }
109 regmatch_t
*m_matches
;
112 #else // WXREGEX_USING_RE_SEARCH
114 // the array of offsets for the matches, the struct used by the GNU lib
118 typedef re_registers
*match_type
;
120 wxRegExMatches(size_t n
)
122 m_matches
.num_regs
= n
;
123 m_matches
.start
= new regoff_t
[n
];
124 m_matches
.end
= new regoff_t
[n
];
129 delete [] m_matches
.start
;
130 delete [] m_matches
.end
;
133 size_t Start(size_t n
) const { return m_matches
.start
[n
]; }
134 size_t End(size_t n
) const { return m_matches
.end
[n
]; }
136 re_registers
*get() { return &m_matches
; }
139 re_registers m_matches
;
142 #endif // WXREGEX_USING_RE_SEARCH
144 // the character type used by the regular expression engine
145 #ifndef WXREGEX_CONVERT_TO_MB
146 typedef wxChar wxRegChar
;
148 typedef char wxRegChar
;
151 // the real implementation of wxRegEx
159 // return true if Compile() had been called successfully
160 bool IsValid() const { return m_isCompiled
; }
163 bool Compile(const wxString
& expr
, int flags
= 0);
164 bool Matches(const wxRegChar
*str
, int flags
165 WXREGEX_IF_NEED_LEN(size_t len
)) const;
166 bool GetMatch(size_t *start
, size_t *len
, size_t index
= 0) const;
167 size_t GetMatchCount() const;
168 int Replace(wxString
*pattern
, const wxString
& replacement
,
169 size_t maxMatches
= 0) const;
172 // return the string containing the error message for the given err code
173 wxString
GetErrorMsg(int errorcode
, bool badconv
) const;
178 m_isCompiled
= false;
183 // free the RE if compiled
188 wx_regfree(&m_RegEx
);
194 // free the RE if any and reinit the members
204 // the subexpressions data
205 wxRegExMatches
*m_Matches
;
208 // true if m_RegEx is valid
213 // ============================================================================
215 // ============================================================================
217 // ----------------------------------------------------------------------------
219 // ----------------------------------------------------------------------------
221 wxRegExImpl::wxRegExImpl()
226 wxRegExImpl::~wxRegExImpl()
231 wxString
wxRegExImpl::GetErrorMsg(int errorcode
, bool badconv
) const
233 #ifdef WXREGEX_CONVERT_TO_MB
234 // currently only needed when using system library in Unicode mode
237 return _("conversion to 8-bit encoding failed");
240 // 'use' badconv to avoid a compiler warning
246 // first get the string length needed
247 int len
= wx_regerror(errorcode
, &m_RegEx
, NULL
, 0);
250 char* szcmbError
= new char[++len
];
252 (void)wx_regerror(errorcode
, &m_RegEx
, szcmbError
, len
);
254 szError
= wxConvertMB2WX(szcmbError
);
255 delete [] szcmbError
;
257 else // regerror() returned 0
259 szError
= _("unknown error");
265 bool wxRegExImpl::Compile(const wxString
& expr
, int flags
)
269 #ifdef WX_NO_REGEX_ADVANCED
270 # define FLAVORS wxRE_BASIC
272 # define FLAVORS (wxRE_ADVANCED | wxRE_BASIC)
273 wxASSERT_MSG( (flags
& FLAVORS
) != FLAVORS
,
274 _T("incompatible flags in wxRegEx::Compile") );
276 wxASSERT_MSG( !(flags
& ~(FLAVORS
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
277 _T("unrecognized flags in wxRegEx::Compile") );
279 // translate our flags to regcomp() ones
281 if ( !(flags
& wxRE_BASIC
) )
282 #ifndef WX_NO_REGEX_ADVANCED
283 if (flags
& wxRE_ADVANCED
)
284 flagsRE
|= REG_ADVANCED
;
287 flagsRE
|= REG_EXTENDED
;
288 if ( flags
& wxRE_ICASE
)
289 flagsRE
|= REG_ICASE
;
290 if ( flags
& wxRE_NOSUB
)
291 flagsRE
|= REG_NOSUB
;
292 if ( flags
& wxRE_NEWLINE
)
293 flagsRE
|= REG_NEWLINE
;
296 #ifdef WXREGEX_USING_BUILTIN
298 int errorcode
= wx_re_comp(&m_RegEx
, expr
, expr
.length(), flagsRE
);
300 const wxWX2MBbuf conv
= expr
.mbc_str();
301 int errorcode
= conv
? regcomp(&m_RegEx
, conv
, flagsRE
) : REG_BADPAT
;
306 wxLogError(_("Invalid regular expression '%s': %s"),
307 expr
.c_str(), GetErrorMsg(errorcode
, !conv
).c_str());
309 m_isCompiled
= false;
313 // don't allocate the matches array now, but do it later if necessary
314 if ( flags
& wxRE_NOSUB
)
316 // we don't need it at all
321 // we will alloc the array later (only if really needed) but count
322 // the number of sub-expressions in the regex right now
324 // there is always one for the whole expression
327 // and some more for bracketed subexperessions
328 for ( const wxChar
*cptr
= expr
.c_str(); *cptr
; cptr
++ )
330 if ( *cptr
== _T('\\') )
332 // in basic RE syntax groups are inside \(...\)
333 if ( *++cptr
== _T('(') && (flags
& wxRE_BASIC
) )
338 else if ( *cptr
== _T('(') && !(flags
& wxRE_BASIC
) )
340 // we know that the previous character is not an unquoted
341 // backslash because it would have been eaten above, so we
342 // have a bare '(' and this indicates a group start for the
343 // extended syntax. '(?' is used for extensions by perl-
344 // like REs (e.g. advanced), and is not valid for POSIX
345 // extended, so ignore them always.
346 if ( cptr
[1] != _T('?') )
358 #ifdef WXREGEX_USING_RE_SEARCH
360 // On GNU, regexec is implemented as a wrapper around re_search. re_search
361 // requires a length parameter which the POSIX regexec does not have,
362 // therefore regexec must do a strlen on the search text each time it is
363 // called. This can drastically affect performance when matching is done in
364 // a loop along a string, such as during a search and replace. Therefore if
365 // re_search is detected by configure, it is used directly.
367 static int ReSearch(const regex_t
*preg
,
370 re_registers
*matches
,
373 regex_t
*pattern
= wx_const_cast(regex_t
*, preg
);
375 pattern
->not_bol
= (eflags
& REG_NOTBOL
) != 0;
376 pattern
->not_eol
= (eflags
& REG_NOTEOL
) != 0;
377 pattern
->regs_allocated
= REGS_FIXED
;
379 int ret
= re_search(pattern
, text
, len
, 0, len
, matches
);
380 return ret
>= 0 ? 0 : REG_NOMATCH
;
383 #endif // WXREGEX_USING_RE_SEARCH
385 bool wxRegExImpl::Matches(const wxRegChar
*str
,
387 WXREGEX_IF_NEED_LEN(size_t len
)) const
389 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
391 // translate our flags to regexec() ones
392 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
393 _T("unrecognized flags in wxRegEx::Matches") );
396 if ( flags
& wxRE_NOTBOL
)
397 flagsRE
|= REG_NOTBOL
;
398 if ( flags
& wxRE_NOTEOL
)
399 flagsRE
|= REG_NOTEOL
;
401 // allocate matches array if needed
402 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
403 if ( !m_Matches
&& m_nMatches
)
405 self
->m_Matches
= new wxRegExMatches(m_nMatches
);
408 wxRegExMatches::match_type matches
= m_Matches
? m_Matches
->get() : NULL
;
411 #if defined WXREGEX_USING_BUILTIN
412 int rc
= wx_re_exec(&self
->m_RegEx
, str
, len
, NULL
, m_nMatches
, matches
, flagsRE
);
413 #elif defined WXREGEX_USING_RE_SEARCH
414 int rc
= str
? ReSearch(&self
->m_RegEx
, str
, len
, matches
, flagsRE
) : REG_BADPAT
;
416 int rc
= str
? regexec(&self
->m_RegEx
, str
, m_nMatches
, matches
, flagsRE
) : REG_BADPAT
;
422 // matched successfully
427 wxLogError(_("Failed to find match for regular expression: %s"),
428 GetErrorMsg(rc
, !str
).c_str());
437 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
439 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
440 wxCHECK_MSG( m_nMatches
, false, _T("can't use with wxRE_NOSUB") );
441 wxCHECK_MSG( m_Matches
, false, _T("must call Matches() first") );
442 wxCHECK_MSG( index
< m_nMatches
, false, _T("invalid match index") );
445 *start
= m_Matches
->Start(index
);
447 *len
= m_Matches
->End(index
) - m_Matches
->Start(index
);
452 size_t wxRegExImpl::GetMatchCount() const
454 wxCHECK_MSG( IsValid(), 0, _T("must successfully Compile() first") );
455 wxCHECK_MSG( m_nMatches
, 0, _T("can't use with wxRE_NOSUB") );
460 int wxRegExImpl::Replace(wxString
*text
,
461 const wxString
& replacement
,
462 size_t maxMatches
) const
464 wxCHECK_MSG( text
, wxNOT_FOUND
, _T("NULL text in wxRegEx::Replace") );
465 wxCHECK_MSG( IsValid(), wxNOT_FOUND
, _T("must successfully Compile() first") );
468 #ifndef WXREGEX_CONVERT_TO_MB
469 const wxChar
*textstr
= text
->c_str();
470 size_t textlen
= text
->length();
472 const wxWX2MBbuf textstr
= WXREGEX_CHAR(*text
);
475 wxLogError(_("Failed to find match for regular expression: %s"),
476 GetErrorMsg(0, true).c_str());
479 size_t textlen
= strlen(textstr
);
483 // the replacement text
486 // the result, allow 25% extra
488 result
.reserve(5 * textlen
/ 4);
490 // attempt at optimization: don't iterate over the string if it doesn't
491 // contain back references at all
492 bool mayHaveBackrefs
=
493 replacement
.find_first_of(_T("\\&")) != wxString::npos
;
495 if ( !mayHaveBackrefs
)
497 textNew
= replacement
;
500 // the position where we start looking for the match
501 size_t matchStart
= 0;
503 // number of replacement made: we won't make more than maxMatches of them
504 // (unless maxMatches is 0 which doesn't limit the number of replacements)
505 size_t countRepl
= 0;
507 // note that "^" shouldn't match after the first call to Matches() so we
508 // use wxRE_NOTBOL to prevent it from happening
509 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
510 Matches(textstr
+ matchStart
,
511 countRepl
? wxRE_NOTBOL
: 0
512 WXREGEX_IF_NEED_LEN(textlen
- matchStart
)) )
514 // the string possibly contains back references: we need to calculate
515 // the replacement text anew after each match
516 if ( mayHaveBackrefs
)
518 mayHaveBackrefs
= false;
520 textNew
.reserve(replacement
.length());
522 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
524 size_t index
= (size_t)-1;
526 if ( *p
== _T('\\') )
528 if ( wxIsdigit(*++p
) )
532 index
= (size_t)wxStrtoul(p
, &end
, 10);
533 p
= end
- 1; // -1 to compensate for p++ in the loop
535 //else: backslash used as escape character
537 else if ( *p
== _T('&') )
539 // treat this as "\0" for compatbility with ed and such
543 // do we have a back reference?
544 if ( index
!= (size_t)-1 )
548 if ( !GetMatch(&start
, &len
, index
) )
550 wxFAIL_MSG( _T("invalid back reference") );
556 textNew
+= wxString(textstr
+ matchStart
+ start
,
557 *wxConvCurrent
, len
);
559 mayHaveBackrefs
= true;
562 else // ordinary character
570 if ( !GetMatch(&start
, &len
) )
572 // we did have match as Matches() returned true above!
573 wxFAIL_MSG( _T("internal logic error in wxRegEx::Replace") );
578 // an insurance against implementations that don't grow exponentially
579 // to ensure building the result takes linear time
580 if (result
.capacity() < result
.length() + start
+ textNew
.length())
581 result
.reserve(2 * result
.length());
583 #ifndef WXREGEX_CONVERT_TO_MB
584 result
.append(*text
, matchStart
, start
);
586 result
.append(wxString(textstr
+ matchStart
, *wxConvCurrent
, start
));
589 result
.append(textNew
);
596 #ifndef WXREGEX_CONVERT_TO_MB
597 result
.append(*text
, matchStart
, wxString::npos
);
599 result
.append(wxString(textstr
+ matchStart
, *wxConvCurrent
));
606 // ----------------------------------------------------------------------------
607 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
608 // ----------------------------------------------------------------------------
620 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
624 m_impl
= new wxRegExImpl
;
627 if ( !m_impl
->Compile(expr
, flags
) )
629 // error message already given in wxRegExImpl::Compile
639 bool wxRegEx::Matches(const wxChar
*str
, int flags
, size_t len
) const
641 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
644 return m_impl
->Matches(WXREGEX_CHAR(str
), flags
WXREGEX_IF_NEED_LEN(len
));
647 bool wxRegEx::Matches(const wxChar
*str
, int flags
) const
649 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
651 return m_impl
->Matches(WXREGEX_CHAR(str
),
653 WXREGEX_IF_NEED_LEN(wxStrlen(str
)));
656 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
658 wxCHECK_MSG( IsValid(), false, _T("must successfully Compile() first") );
660 return m_impl
->GetMatch(start
, len
, index
);
663 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
666 if ( !GetMatch(&start
, &len
, index
) )
667 return wxEmptyString
;
669 return text
.Mid(start
, len
);
672 size_t wxRegEx::GetMatchCount() const
674 wxCHECK_MSG( IsValid(), 0, _T("must successfully Compile() first") );
676 return m_impl
->GetMatchCount();
679 int wxRegEx::Replace(wxString
*pattern
,
680 const wxString
& replacement
,
681 size_t maxMatches
) const
683 wxCHECK_MSG( IsValid(), wxNOT_FOUND
, _T("must successfully Compile() first") );
685 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
688 #endif // wxUSE_REGEX