]>
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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
22 #pragma implementation "regex.h"
25 // For compilers that support precompilation, includes "wx.h".
26 #include "wx/wxprec.h"
35 #include "wx/object.h"
36 #include "wx/string.h"
41 // FreeBSD, Watcom and DMars require this, CW doesn't have nor need it.
42 // Others also don't seem to need it. If you have an error related to
43 // (not) including <sys/types.h> please report details to
44 // wx-dev@lists.wxwindows.org
45 #if defined(__UNIX__) || defined(__WATCOMC__) || defined(__DIGITALMARS__)
46 # include <sys/types.h>
52 // ----------------------------------------------------------------------------
54 // ----------------------------------------------------------------------------
56 // the real implementation of wxRegEx
64 // return TRUE if Compile() had been called successfully
65 bool IsValid() const { return m_isCompiled
; }
68 bool Compile(const wxString
& expr
, int flags
= 0);
69 bool Matches(const wxChar
*str
, int flags
= 0) const;
70 bool GetMatch(size_t *start
, size_t *len
, size_t index
= 0) const;
71 int Replace(wxString
*pattern
, const wxString
& replacement
,
72 size_t maxMatches
= 0) const;
75 // return the string containing the error message for the given err code
76 wxString
GetErrorMsg(int errorcode
, bool badconv
) const;
86 // free the RE if compiled
97 // free the RE if any and reinit the members
108 // the subexpressions data
109 regmatch_t
*m_Matches
;
112 // TRUE if m_RegEx is valid
116 // ============================================================================
118 // ============================================================================
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 wxRegExImpl::wxRegExImpl()
129 wxRegExImpl::~wxRegExImpl()
134 wxString
wxRegExImpl::GetErrorMsg(int errorcode
, bool badconv
) const
136 #if wxUSE_UNICODE && !defined(__REG_NOFRONT)
137 // currently only needed when using system library in Unicode mode
140 return _("conversion to 8-bit encoding failed");
143 // 'use' badconv to avoid a compiler warning
149 // first get the string length needed
150 int len
= regerror(errorcode
, &m_RegEx
, NULL
, 0);
153 char* szcmbError
= new char[++len
];
155 (void)regerror(errorcode
, &m_RegEx
, szcmbError
, len
);
157 szError
= wxConvertMB2WX(szcmbError
);
158 delete [] szcmbError
;
160 else // regerror() returned 0
162 szError
= _("unknown error");
168 bool wxRegExImpl::Compile(const wxString
& expr
, int flags
)
172 #ifdef WX_NO_REGEX_ADVANCED
173 # define FLAVORS wxRE_BASIC
175 # define FLAVORS (wxRE_ADVANCED | wxRE_BASIC)
176 wxASSERT_MSG( (flags
& FLAVORS
) != FLAVORS
,
177 _T("incompatible flags in wxRegEx::Compile") );
179 wxASSERT_MSG( !(flags
& ~(FLAVORS
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
180 _T("unrecognized flags in wxRegEx::Compile") );
182 // translate our flags to regcomp() ones
184 if ( !(flags
& wxRE_BASIC
) )
185 #ifndef WX_NO_REGEX_ADVANCED
186 if (flags
& wxRE_ADVANCED
)
187 flagsRE
|= REG_ADVANCED
;
190 flagsRE
|= REG_EXTENDED
;
191 if ( flags
& wxRE_ICASE
)
192 flagsRE
|= REG_ICASE
;
193 if ( flags
& wxRE_NOSUB
)
194 flagsRE
|= REG_NOSUB
;
195 if ( flags
& wxRE_NEWLINE
)
196 flagsRE
|= REG_NEWLINE
;
201 int errorcode
= re_comp(&m_RegEx
, expr
, expr
.length(), flagsRE
);
203 const wxWX2MBbuf conv
= expr
.mbc_str();
204 int errorcode
= conv
? regcomp(&m_RegEx
, conv
, flagsRE
) : REG_BADPAT
;
209 wxLogError(_("Invalid regular expression '%s': %s"),
210 expr
.c_str(), GetErrorMsg(errorcode
, !conv
).c_str());
212 m_isCompiled
= FALSE
;
216 // don't allocate the matches array now, but do it later if necessary
217 if ( flags
& wxRE_NOSUB
)
219 // we don't need it at all
224 // we will alloc the array later (only if really needed) but count
225 // the number of sub-expressions in the regex right now
227 // there is always one for the whole expression
230 // and some more for bracketed subexperessions
231 for ( const wxChar
*cptr
= expr
.c_str(); *cptr
; cptr
++ )
233 if ( *cptr
== _T('\\') )
235 // in basic RE syntax groups are inside \(...\)
236 if ( *++cptr
== _T('(') && (flags
& wxRE_BASIC
) )
241 else if ( *cptr
== _T('(') && !(flags
& wxRE_BASIC
) )
243 // we know that the previous character is not an unquoted
244 // backslash because it would have been eaten above, so we
245 // have a bar '(' and this indicates a group start for the
258 bool wxRegExImpl::Matches(const wxChar
*str
, int flags
) const
260 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
262 // translate our flags to regexec() ones
263 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
264 _T("unrecognized flags in wxRegEx::Matches") );
267 if ( flags
& wxRE_NOTBOL
)
268 flagsRE
|= REG_NOTBOL
;
269 if ( flags
& wxRE_NOTEOL
)
270 flagsRE
|= REG_NOTEOL
;
272 // allocate matches array if needed
273 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
274 if ( !m_Matches
&& m_nMatches
)
276 self
->m_Matches
= new regmatch_t
[m_nMatches
];
282 int rc
= re_exec(&self
->m_RegEx
, str
, wxStrlen(str
), NULL
, m_nMatches
, m_Matches
, flagsRE
);
284 const wxWX2MBbuf conv
= wxConvertWX2MB(str
);
285 int rc
= conv
? regexec(&self
->m_RegEx
, conv
, m_nMatches
, m_Matches
, flagsRE
) : REG_BADPAT
;
291 // matched successfully
296 wxLogError(_("Failed to match '%s' in regular expression: %s"),
297 str
, GetErrorMsg(rc
, !conv
).c_str());
306 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
308 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
309 wxCHECK_MSG( m_Matches
, FALSE
, _T("can't use with wxRE_NOSUB") );
310 wxCHECK_MSG( index
< m_nMatches
, FALSE
, _T("invalid match index") );
312 const regmatch_t
& match
= m_Matches
[index
];
315 *start
= match
.rm_so
;
317 *len
= match
.rm_eo
- match
.rm_so
;
322 int wxRegExImpl::Replace(wxString
*text
,
323 const wxString
& replacement
,
324 size_t maxMatches
) const
326 wxCHECK_MSG( text
, -1, _T("NULL text in wxRegEx::Replace") );
327 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
329 // the replacement text
332 // attempt at optimization: don't iterate over the string if it doesn't
333 // contain back references at all
334 bool mayHaveBackrefs
=
335 replacement
.find_first_of(_T("\\&")) != wxString::npos
;
337 if ( !mayHaveBackrefs
)
339 textNew
= replacement
;
342 // the position where we start looking for the match
344 // NB: initial version had a nasty bug because it used a wxChar* instead of
345 // an index but the problem is that replace() in the loop invalidates
346 // all pointers into the string so we have to use indices instead
347 size_t matchStart
= 0;
349 // number of replacement made: we won't make more than maxMatches of them
350 // (unless maxMatches is 0 which doesn't limit the number of replacements)
351 size_t countRepl
= 0;
353 // note that "^" shouldn't match after the first call to Matches() so we
354 // use wxRE_NOTBOL to prevent it from happening
355 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
356 Matches(text
->c_str() + matchStart
, countRepl
? wxRE_NOTBOL
: 0) )
358 // the string possibly contains back references: we need to calculate
359 // the replacement text anew after each match
360 if ( mayHaveBackrefs
)
362 mayHaveBackrefs
= FALSE
;
364 textNew
.reserve(replacement
.length());
366 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
368 size_t index
= (size_t)-1;
370 if ( *p
== _T('\\') )
372 if ( wxIsdigit(*++p
) )
376 index
= (size_t)wxStrtoul(p
, &end
, 10);
377 p
= end
- 1; // -1 to compensate for p++ in the loop
379 //else: backslash used as escape character
381 else if ( *p
== _T('&') )
383 // treat this as "\0" for compatbility with ed and such
387 // do we have a back reference?
388 if ( index
!= (size_t)-1 )
392 if ( !GetMatch(&start
, &len
, index
) )
394 wxFAIL_MSG( _T("invalid back reference") );
400 textNew
+= wxString(text
->c_str() + matchStart
+ start
,
403 mayHaveBackrefs
= TRUE
;
406 else // ordinary character
414 if ( !GetMatch(&start
, &len
) )
416 // we did have match as Matches() returned true above!
417 wxFAIL_MSG( _T("internal logic error in wxRegEx::Replace") );
423 text
->replace(matchStart
, len
, textNew
);
427 matchStart
+= textNew
.length();
433 // ----------------------------------------------------------------------------
434 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
435 // ----------------------------------------------------------------------------
448 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
452 m_impl
= new wxRegExImpl
;
455 if ( !m_impl
->Compile(expr
, flags
) )
457 // error message already given in wxRegExImpl::Compile
467 bool wxRegEx::Matches(const wxChar
*str
, int flags
) const
469 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
471 return m_impl
->Matches(str
, flags
);
474 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
476 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
478 return m_impl
->GetMatch(start
, len
, index
);
481 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
484 if ( !GetMatch(&start
, &len
, index
) )
485 return wxEmptyString
;
487 return text
.Mid(start
, len
);
490 int wxRegEx::Replace(wxString
*pattern
,
491 const wxString
& replacement
,
492 size_t maxMatches
) const
494 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
496 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
499 #endif // wxUSE_REGEX