]>
git.saurik.com Git - wxWidgets.git/blob - src/common/regex.cpp
38d5e6431d064f9566058021822cacba766c2ebd
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 require this, it probably doesn't hurt for others
42 #if defined(__UNIX__) || defined(__WATCOMC__) || defined(__DIGITALMARS__)
43 #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
) 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
) const
138 // first get the string length needed
139 int len
= regerror(errorcode
, &m_RegEx
, NULL
, 0);
145 wxCharBuffer
buf(len
);
147 (void)regerror(errorcode
, &m_RegEx
, (char *)buf
.data(), len
);
149 msg
= wxString(buf
.data(), wxConvLibc
);
151 (void)regerror(errorcode
, &m_RegEx
, msg
.GetWriteBuf(len
), len
);
154 #endif // Unicode/!Unicode
156 else // regerror() returned 0
158 msg
= _("unknown error");
164 bool wxRegExImpl::Compile(const wxString
& expr
, int flags
)
168 // translate our flags to regcomp() ones
169 wxASSERT_MSG( !(flags
&
170 ~(wxRE_BASIC
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
171 _T("unrecognized flags in wxRegEx::Compile") );
174 if ( !(flags
& wxRE_BASIC
) )
175 flagsRE
|= REG_EXTENDED
;
176 if ( flags
& wxRE_ICASE
)
177 flagsRE
|= REG_ICASE
;
178 if ( flags
& wxRE_NOSUB
)
179 flagsRE
|= REG_NOSUB
;
180 if ( flags
& wxRE_NEWLINE
)
181 flagsRE
|= REG_NEWLINE
;
186 int errorcode
= wx_regcomp(&m_RegEx
, expr
, expr
.Length(), flagsRE
);
188 int errorcode
= regcomp(&m_RegEx
, expr
.mb_str(), flagsRE
);
193 wxLogError(_("Invalid regular expression '%s': %s"),
194 expr
.c_str(), GetErrorMsg(errorcode
).c_str());
196 m_isCompiled
= FALSE
;
200 // don't allocate the matches array now, but do it later if necessary
201 if ( flags
& wxRE_NOSUB
)
203 // we don't need it at all
208 // we will alloc the array later (only if really needed) but count
209 // the number of sub-expressions in the regex right now
211 // there is always one for the whole expression
214 // and some more for bracketed subexperessions
215 for ( const wxChar
*cptr
= expr
.c_str(); *cptr
; cptr
++ )
217 if ( *cptr
== _T('\\') )
219 // in basic RE syntax groups are inside \(...\)
220 if ( *++cptr
== _T('(') && (flags
& wxRE_BASIC
) )
225 else if ( *cptr
== _T('(') && !(flags
& wxRE_BASIC
) )
227 // we know that the previous character is not an unquoted
228 // backslash because it would have been eaten above, so we
229 // have a bar '(' and this indicates a group start for the
242 bool wxRegExImpl::Matches(const wxChar
*str
, int flags
) const
244 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
246 // translate our flags to regexec() ones
247 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
248 _T("unrecognized flags in wxRegEx::Matches") );
251 if ( flags
& wxRE_NOTBOL
)
252 flagsRE
|= REG_NOTBOL
;
253 if ( flags
& wxRE_NOTEOL
)
254 flagsRE
|= REG_NOTEOL
;
256 // allocate matches array if needed
257 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
258 if ( !m_Matches
&& m_nMatches
)
260 self
->m_Matches
= new regmatch_t
[m_nMatches
];
264 #ifdef wxUSE_NEW_REGEX
266 int rc
= wx_regexec(&self
->m_RegEx
, str
, wxStrlen(str
), &rd
, m_nMatches
, m_Matches
, flagsRE
);
268 int rc
= regexec(&self
->m_RegEx
, wxConvertWX2MB(str
), m_nMatches
, m_Matches
, flagsRE
);
274 // matched successfully
279 wxLogError(_("Failed to match '%s' in regular expression: %s"),
280 str
, GetErrorMsg(rc
).c_str());
289 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
291 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
292 wxCHECK_MSG( m_Matches
, FALSE
, _T("can't use with wxRE_NOSUB") );
293 wxCHECK_MSG( index
< m_nMatches
, FALSE
, _T("invalid match index") );
295 const regmatch_t
& match
= m_Matches
[index
];
298 *start
= match
.rm_so
;
300 *len
= match
.rm_eo
- match
.rm_so
;
305 int wxRegExImpl::Replace(wxString
*text
,
306 const wxString
& replacement
,
307 size_t maxMatches
) const
309 wxCHECK_MSG( text
, -1, _T("NULL text in wxRegEx::Replace") );
310 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
312 // the replacement text
315 // attempt at optimization: don't iterate over the string if it doesn't
316 // contain back references at all
317 bool mayHaveBackrefs
=
318 replacement
.find_first_of(_T("\\&")) != wxString::npos
;
320 if ( !mayHaveBackrefs
)
322 textNew
= replacement
;
325 // the position where we start looking for the match
327 // NB: initial version had a nasty bug because it used a wxChar* instead of
328 // an index but the problem is that replace() in the loop invalidates
329 // all pointers into the string so we have to use indices instead
330 size_t matchStart
= 0;
332 // number of replacement made: we won't make more than maxMatches of them
333 // (unless maxMatches is 0 which doesn't limit the number of replacements)
334 size_t countRepl
= 0;
336 // note that "^" shouldn't match after the first call to Matches() so we
337 // use wxRE_NOTBOL to prevent it from happening
338 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
339 Matches(text
->c_str() + matchStart
, countRepl
? wxRE_NOTBOL
: 0) )
341 // the string possibly contains back references: we need to calculate
342 // the replacement text anew after each match
343 if ( mayHaveBackrefs
)
345 mayHaveBackrefs
= FALSE
;
347 textNew
.reserve(replacement
.length());
349 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
351 size_t index
= (size_t)-1;
353 if ( *p
== _T('\\') )
355 if ( wxIsdigit(*++p
) )
359 index
= (size_t)wxStrtoul(p
, &end
, 10);
360 p
= end
- 1; // -1 to compensate for p++ in the loop
362 //else: backslash used as escape character
364 else if ( *p
== _T('&') )
366 // treat this as "\0" for compatbility with ed and such
370 // do we have a back reference?
371 if ( index
!= (size_t)-1 )
375 if ( !GetMatch(&start
, &len
, index
) )
377 wxFAIL_MSG( _T("invalid back reference") );
383 textNew
+= wxString(text
->c_str() + matchStart
+ start
,
386 mayHaveBackrefs
= TRUE
;
389 else // ordinary character
397 if ( !GetMatch(&start
, &len
) )
399 // we did have match as Matches() returned true above!
400 wxFAIL_MSG( _T("internal logic error in wxRegEx::Replace") );
406 text
->replace(matchStart
, len
, textNew
);
410 matchStart
+= textNew
.length();
416 // ----------------------------------------------------------------------------
417 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
418 // ----------------------------------------------------------------------------
431 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
435 m_impl
= new wxRegExImpl
;
438 if ( !m_impl
->Compile(expr
, flags
) )
440 // error message already given in wxRegExImpl::Compile
450 bool wxRegEx::Matches(const wxChar
*str
, int flags
) const
452 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
454 return m_impl
->Matches(str
, flags
);
457 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
459 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
461 return m_impl
->GetMatch(start
, len
, index
);
464 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
467 if ( !GetMatch(&start
, &len
, index
) )
468 return wxEmptyString
;
470 return text
.Mid(start
, len
);
473 int wxRegEx::Replace(wxString
*pattern
,
474 const wxString
& replacement
,
475 size_t maxMatches
) const
477 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
479 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
482 #endif // wxUSE_REGEX