]>
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 // ----------------------------------------------------------------------------
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 requires this, it probably doesn't hurt for others
43 #include <sys/types.h>
50 // ----------------------------------------------------------------------------
52 // ----------------------------------------------------------------------------
54 // the real implementation of wxRegEx
62 // return TRUE if Compile() had been called successfully
63 bool IsValid() const { return m_isCompiled
; }
66 bool Compile(const wxString
& expr
, int flags
= 0);
67 bool Matches(const wxChar
*str
, int flags
= 0) const;
68 bool GetMatch(size_t *start
, size_t *len
, size_t index
= 0) const;
69 int Replace(wxString
*pattern
, const wxString
& replacement
,
70 size_t maxMatches
= 0) const;
73 // return the string containing the error message for the given err code
74 wxString
GetErrorMsg(int errorcode
) const;
76 // free the RE if compiled
90 // the subexpressions data
91 regmatch_t
*m_Matches
;
94 // TRUE if m_RegEx is valid
98 // ============================================================================
100 // ============================================================================
102 // ----------------------------------------------------------------------------
104 // ----------------------------------------------------------------------------
106 wxRegExImpl::wxRegExImpl()
108 m_isCompiled
= FALSE
;
113 wxRegExImpl::~wxRegExImpl()
120 wxString
wxRegExImpl::GetErrorMsg(int errorcode
) const
124 // first get the string length needed
125 int len
= regerror(errorcode
, &m_RegEx
, NULL
, 0);
130 (void)regerror(errorcode
, &m_RegEx
, msg
.GetWriteBuf(len
), len
);
134 else // regerror() returned 0
136 msg
= _("unknown error");
142 bool wxRegExImpl::Compile(const wxString
& expr
, int flags
)
146 // translate our flags to regcomp() ones
147 wxASSERT_MSG( !(flags
&
148 ~(wxRE_BASIC
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
149 _T("unrecognized flags in wxRegEx::Compile") );
152 if ( !(flags
& wxRE_BASIC
) )
153 flagsRE
|= REG_EXTENDED
;
154 if ( flags
& wxRE_ICASE
)
155 flagsRE
|= REG_ICASE
;
156 if ( flags
& wxRE_NOSUB
)
157 flagsRE
|= REG_NOSUB
;
158 if ( flags
& wxRE_NEWLINE
)
159 flagsRE
|= REG_NEWLINE
;
162 int errorcode
= regcomp(&m_RegEx
, expr
, flagsRE
);
165 wxLogError(_("Invalid regular expression '%s': %s"),
166 expr
.c_str(), GetErrorMsg(errorcode
).c_str());
168 m_isCompiled
= FALSE
;
172 // don't allocate the matches array now, but do it later if necessary
173 if ( flags
& wxRE_NOSUB
)
175 // we don't need it at all
180 // we will alloc the array later (only if really needed) but count
181 // the number of sub-expressions in the regex right now
183 // there is always one for the whole expression
186 // and some more for bracketed subexperessions
187 const wxChar
*cptr
= expr
.c_str();
188 wxChar prev
= _T('\0');
189 while ( *cptr
!= _T('\0') )
191 // is this a subexpr start, i.e. "(" for extended regex or
192 // "\(" for a basic one?
193 if ( *cptr
== _T('(') &&
194 (flags
& wxRE_BASIC
? prev
== _T('\\')
195 : prev
!= _T('\\')) )
211 bool wxRegExImpl::Matches(const wxChar
*str
, int flags
) const
213 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
215 // translate our flags to regexec() ones
216 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
217 _T("unrecognized flags in wxRegEx::Matches") );
220 if ( flags
& wxRE_NOTBOL
)
221 flagsRE
|= REG_NOTBOL
;
222 if ( flags
& wxRE_NOTEOL
)
223 flagsRE
|= REG_NOTEOL
;
225 // allocate matches array if needed
226 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
227 if ( !m_Matches
&& m_nMatches
)
229 self
->m_Matches
= new regmatch_t
[m_nMatches
];
233 int rc
= regexec(&self
->m_RegEx
, str
, m_nMatches
, m_Matches
, flagsRE
);
238 // matched successfully
243 wxLogError(_("Failed to match '%s' in regular expression: %s"),
244 str
, GetErrorMsg(rc
).c_str());
253 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
255 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
256 wxCHECK_MSG( m_Matches
, FALSE
, _T("can't use with wxRE_NOSUB") );
257 wxCHECK_MSG( index
< m_nMatches
, FALSE
, _T("invalid match index") );
259 const regmatch_t
& match
= m_Matches
[index
];
262 *start
= match
.rm_so
;
264 *len
= match
.rm_eo
- match
.rm_so
;
269 int wxRegExImpl::Replace(wxString
*text
,
270 const wxString
& replacement
,
271 size_t maxMatches
) const
273 wxCHECK_MSG( text
, -1, _T("NULL text in wxRegEx::Replace") );
274 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
276 // the replacement text
279 // attempt at optimization: don't iterate over the string if it doesn't
280 // contain back references at all
281 bool mayHaveBackrefs
=
282 replacement
.find_first_of(_T("\\&")) != wxString::npos
;
284 if ( !mayHaveBackrefs
)
286 textNew
= replacement
;
289 // the position where we start looking for the match
291 // NB: initial version had a nasty bug because it used a wxChar* instead of
292 // an index but the problem is that replace() in the loop invalidates
293 // all pointers into the string so we have to use indices instead
294 size_t matchStart
= 0;
296 // number of replacement made: we won't make more than maxMatches of them
297 // (unless maxMatches is 0 which doesn't limit the number of replacements)
298 size_t countRepl
= 0;
300 // note that "^" shouldn't match after the first call to Matches() so we
301 // use wxRE_NOTBOL to prevent it from happening
302 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
303 Matches(text
->c_str() + matchStart
, countRepl
? wxRE_NOTBOL
: 0) )
305 // the string possibly contains back references: we need to calculate
306 // the replacement text anew after each match
307 if ( mayHaveBackrefs
)
309 mayHaveBackrefs
= FALSE
;
311 textNew
.reserve(replacement
.length());
313 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
315 size_t index
= (size_t)-1;
317 if ( *p
== _T('\\') )
319 if ( wxIsdigit(*++p
) )
323 index
= (size_t)wxStrtoul(p
, &end
, 10);
324 p
= end
- 1; // -1 to compensate for p++ in the loop
326 //else: backslash used as escape character
328 else if ( *p
== _T('&') )
330 // treat this as "\0" for compatbility with ed and such
334 // do we have a back reference?
335 if ( index
!= (size_t)-1 )
339 if ( !GetMatch(&start
, &len
, index
) )
341 wxFAIL_MSG( _T("invalid back reference") );
347 textNew
+= wxString(text
->c_str() + matchStart
+ start
,
350 mayHaveBackrefs
= TRUE
;
353 else // ordinary character
361 if ( !GetMatch(&start
, &len
) )
363 // we did have match as Matches() returned true above!
364 wxFAIL_MSG( _T("internal logic error in wxRegEx::Replace") );
370 text
->replace(matchStart
, len
, textNew
);
374 matchStart
+= textNew
.length();
380 // ----------------------------------------------------------------------------
381 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
382 // ----------------------------------------------------------------------------
395 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
399 m_impl
= new wxRegExImpl
;
402 if ( !m_impl
->Compile(expr
, flags
) )
404 // error message already given in wxRegExImpl::Compile
414 bool wxRegEx::Matches(const wxChar
*str
, int flags
) const
416 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
418 return m_impl
->Matches(str
, flags
);
421 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
423 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
425 return m_impl
->GetMatch(start
, len
, index
);
428 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
431 if ( !GetMatch(&start
, &len
, index
) )
432 return wxEmptyString
;
434 return text
.Mid(start
, len
);
437 int wxRegEx::Replace(wxString
*pattern
,
438 const wxString
& replacement
,
439 size_t maxMatches
) const
441 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
443 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
446 #endif // wxUSE_REGEX