]>
git.saurik.com Git - wxWidgets.git/blob - src/common/regex.cpp
7d0efb3acc36c9fb8ad650b083b4723996b7a3fe
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>
56 # if !defined(wxUSE_BUILTIN_REGEX)
57 # error "Unicode not supported with system regex, please reconfigure with --with-regex=builtin"
61 // ----------------------------------------------------------------------------
63 // ----------------------------------------------------------------------------
65 // the real implementation of wxRegEx
73 // return TRUE if Compile() had been called successfully
74 bool IsValid() const { return m_isCompiled
; }
77 bool Compile(const wxString
& expr
, int flags
= 0);
78 bool Matches(const wxChar
*str
, int flags
= 0) const;
79 bool GetMatch(size_t *start
, size_t *len
, size_t index
= 0) const;
80 int Replace(wxString
*pattern
, const wxString
& replacement
,
81 size_t maxMatches
= 0) const;
84 // return the string containing the error message for the given err code
85 wxString
GetErrorMsg(int errorcode
) const;
95 // free the RE if compiled
106 // free the RE if any and reinit the members
117 // the subexpressions data
118 regmatch_t
*m_Matches
;
121 // TRUE if m_RegEx is valid
125 // ============================================================================
127 // ============================================================================
129 // ----------------------------------------------------------------------------
131 // ----------------------------------------------------------------------------
133 wxRegExImpl::wxRegExImpl()
138 wxRegExImpl::~wxRegExImpl()
143 wxString
wxRegExImpl::GetErrorMsg(int errorcode
) const
147 // first get the string length needed
148 int len
= regerror(errorcode
, &m_RegEx
, NULL
, 0);
151 char* szcmbError
= new char[++len
];
153 (void)regerror(errorcode
, &m_RegEx
, szcmbError
, len
);
155 szError
= wxConvertMB2WX(szcmbError
);
156 delete [] szcmbError
;
158 else // regerror() returned 0
160 szError
= _("unknown error");
166 bool wxRegExImpl::Compile(const wxString
& expr
, int flags
)
170 // translate our flags to regcomp() ones
171 wxASSERT_MSG( !(flags
&
172 ~(wxRE_BASIC
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
173 _T("unrecognized flags in wxRegEx::Compile") );
176 if ( !(flags
& wxRE_BASIC
) )
177 flagsRE
|= REG_EXTENDED
;
178 if ( flags
& wxRE_ICASE
)
179 flagsRE
|= REG_ICASE
;
180 if ( flags
& wxRE_NOSUB
)
181 flagsRE
|= REG_NOSUB
;
182 if ( flags
& wxRE_NEWLINE
)
183 flagsRE
|= REG_NEWLINE
;
187 int errorcode
= regcomp(&m_RegEx
, expr
, flagsRE
);
191 wxLogError(_("Invalid regular expression '%s': %s"),
192 expr
.c_str(), GetErrorMsg(errorcode
).c_str());
194 m_isCompiled
= FALSE
;
198 // don't allocate the matches array now, but do it later if necessary
199 if ( flags
& wxRE_NOSUB
)
201 // we don't need it at all
206 // we will alloc the array later (only if really needed) but count
207 // the number of sub-expressions in the regex right now
209 // there is always one for the whole expression
212 // and some more for bracketed subexperessions
213 for ( const wxChar
*cptr
= expr
.c_str(); *cptr
; cptr
++ )
215 if ( *cptr
== _T('\\') )
217 // in basic RE syntax groups are inside \(...\)
218 if ( *++cptr
== _T('(') && (flags
& wxRE_BASIC
) )
223 else if ( *cptr
== _T('(') && !(flags
& wxRE_BASIC
) )
225 // we know that the previous character is not an unquoted
226 // backslash because it would have been eaten above, so we
227 // have a bar '(' and this indicates a group start for the
240 bool wxRegExImpl::Matches(const wxChar
*str
, int flags
) const
242 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
244 // translate our flags to regexec() ones
245 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
246 _T("unrecognized flags in wxRegEx::Matches") );
249 if ( flags
& wxRE_NOTBOL
)
250 flagsRE
|= REG_NOTBOL
;
251 if ( flags
& wxRE_NOTEOL
)
252 flagsRE
|= REG_NOTEOL
;
254 // allocate matches array if needed
255 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
256 if ( !m_Matches
&& m_nMatches
)
258 self
->m_Matches
= new regmatch_t
[m_nMatches
];
262 int rc
= regexec(&self
->m_RegEx
, str
, m_nMatches
, m_Matches
, flagsRE
);
267 // matched successfully
272 wxLogError(_("Failed to match '%s' in regular expression: %s"),
273 str
, GetErrorMsg(rc
).c_str());
282 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
284 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
285 wxCHECK_MSG( m_Matches
, FALSE
, _T("can't use with wxRE_NOSUB") );
286 wxCHECK_MSG( index
< m_nMatches
, FALSE
, _T("invalid match index") );
288 const regmatch_t
& match
= m_Matches
[index
];
291 *start
= match
.rm_so
;
293 *len
= match
.rm_eo
- match
.rm_so
;
298 int wxRegExImpl::Replace(wxString
*text
,
299 const wxString
& replacement
,
300 size_t maxMatches
) const
302 wxCHECK_MSG( text
, -1, _T("NULL text in wxRegEx::Replace") );
303 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
305 // the replacement text
308 // attempt at optimization: don't iterate over the string if it doesn't
309 // contain back references at all
310 bool mayHaveBackrefs
=
311 replacement
.find_first_of(_T("\\&")) != wxString::npos
;
313 if ( !mayHaveBackrefs
)
315 textNew
= replacement
;
318 // the position where we start looking for the match
320 // NB: initial version had a nasty bug because it used a wxChar* instead of
321 // an index but the problem is that replace() in the loop invalidates
322 // all pointers into the string so we have to use indices instead
323 size_t matchStart
= 0;
325 // number of replacement made: we won't make more than maxMatches of them
326 // (unless maxMatches is 0 which doesn't limit the number of replacements)
327 size_t countRepl
= 0;
329 // note that "^" shouldn't match after the first call to Matches() so we
330 // use wxRE_NOTBOL to prevent it from happening
331 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
332 Matches(text
->c_str() + matchStart
, countRepl
? wxRE_NOTBOL
: 0) )
334 // the string possibly contains back references: we need to calculate
335 // the replacement text anew after each match
336 if ( mayHaveBackrefs
)
338 mayHaveBackrefs
= FALSE
;
340 textNew
.reserve(replacement
.length());
342 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
344 size_t index
= (size_t)-1;
346 if ( *p
== _T('\\') )
348 if ( wxIsdigit(*++p
) )
352 index
= (size_t)wxStrtoul(p
, &end
, 10);
353 p
= end
- 1; // -1 to compensate for p++ in the loop
355 //else: backslash used as escape character
357 else if ( *p
== _T('&') )
359 // treat this as "\0" for compatbility with ed and such
363 // do we have a back reference?
364 if ( index
!= (size_t)-1 )
368 if ( !GetMatch(&start
, &len
, index
) )
370 wxFAIL_MSG( _T("invalid back reference") );
376 textNew
+= wxString(text
->c_str() + matchStart
+ start
,
379 mayHaveBackrefs
= TRUE
;
382 else // ordinary character
390 if ( !GetMatch(&start
, &len
) )
392 // we did have match as Matches() returned true above!
393 wxFAIL_MSG( _T("internal logic error in wxRegEx::Replace") );
399 text
->replace(matchStart
, len
, textNew
);
403 matchStart
+= textNew
.length();
409 // ----------------------------------------------------------------------------
410 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
411 // ----------------------------------------------------------------------------
424 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
428 m_impl
= new wxRegExImpl
;
431 if ( !m_impl
->Compile(expr
, flags
) )
433 // error message already given in wxRegExImpl::Compile
443 bool wxRegEx::Matches(const wxChar
*str
, int flags
) const
445 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
447 return m_impl
->Matches(str
, flags
);
450 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
452 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
454 return m_impl
->GetMatch(start
, len
, index
);
457 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
460 if ( !GetMatch(&start
, &len
, index
) )
461 return wxEmptyString
;
463 return text
.Mid(start
, len
);
466 int wxRegEx::Replace(wxString
*pattern
,
467 const wxString
& replacement
,
468 size_t maxMatches
) const
470 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
472 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
475 #endif // wxUSE_REGEX