]>
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
;
112 wxRegExImpl::~wxRegExImpl()
119 wxString
wxRegExImpl::GetErrorMsg(int errorcode
) const
123 // first get the string length needed
124 int len
= regerror(errorcode
, &m_RegEx
, NULL
, 0);
129 (void)regerror(errorcode
, &m_RegEx
, msg
.GetWriteBuf(len
), len
);
133 else // regerror() returned 0
135 msg
= _("unknown error");
141 bool wxRegExImpl::Compile(const wxString
& expr
, int flags
)
145 // translate our flags to regcomp() ones
146 wxASSERT_MSG( !(flags
&
147 ~(wxRE_BASIC
| wxRE_ICASE
| wxRE_NOSUB
| wxRE_NEWLINE
)),
148 _T("unrecognized flags in wxRegEx::Compile") );
151 if ( !(flags
& wxRE_BASIC
) )
152 flagsRE
|= REG_EXTENDED
;
153 if ( flags
& wxRE_ICASE
)
154 flagsRE
|= REG_ICASE
;
155 if ( flags
& wxRE_NOSUB
)
156 flagsRE
|= REG_NOSUB
;
157 if ( flags
& wxRE_NEWLINE
)
158 flagsRE
|= REG_NEWLINE
;
161 int errorcode
= regcomp(&m_RegEx
, expr
, flagsRE
);
164 wxLogError(_("Invalid regular expression '%s': %s"),
165 expr
.c_str(), GetErrorMsg(errorcode
).c_str());
167 m_isCompiled
= FALSE
;
171 // don't allocate the matches array now, but do it later if necessary
172 if ( flags
& wxRE_NOSUB
)
174 // we don't need it at all
180 m_nMatches
= WX_REGEX_MAXMATCHES
;
189 bool wxRegExImpl::Matches(const wxChar
*str
, int flags
) const
191 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
193 // translate our flags to regexec() ones
194 wxASSERT_MSG( !(flags
& ~(wxRE_NOTBOL
| wxRE_NOTEOL
)),
195 _T("unrecognized flags in wxRegEx::Matches") );
198 if ( flags
& wxRE_NOTBOL
)
199 flagsRE
|= REG_NOTBOL
;
200 if ( flags
& wxRE_NOTEOL
)
201 flagsRE
|= REG_NOTEOL
;
203 // allocate matches array if needed
204 wxRegExImpl
*self
= wxConstCast(this, wxRegExImpl
);
205 if ( !m_Matches
&& m_nMatches
)
207 self
->m_Matches
= new regmatch_t
[m_nMatches
];
211 int rc
= regexec(&self
->m_RegEx
, str
, m_nMatches
, m_Matches
, flagsRE
);
216 // matched successfully
221 wxLogError(_("Failed to match '%s' in regular expression: %s"),
222 str
, GetErrorMsg(rc
).c_str());
231 bool wxRegExImpl::GetMatch(size_t *start
, size_t *len
, size_t index
) const
233 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
234 wxCHECK_MSG( m_Matches
, FALSE
, _T("can't use with wxRE_NOSUB") );
235 wxCHECK_MSG( index
< m_nMatches
, FALSE
, _T("invalid match index") );
237 const regmatch_t
& match
= m_Matches
[index
];
238 if ( match
.rm_so
== -1 )
242 *start
= match
.rm_so
;
244 *len
= match
.rm_eo
- match
.rm_so
;
249 int wxRegExImpl::Replace(wxString
*text
,
250 const wxString
& replacement
,
251 size_t maxMatches
) const
253 wxCHECK_MSG( text
, -1, _T("NULL text in wxRegEx::Replace") );
254 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
256 // the replacement text
259 // attempt at optimization: don't iterate over the string if it doesn't
260 // contain back references at all
261 bool mayHaveBackrefs
=
262 replacement
.find_first_of(_T("\\&")) != wxString::npos
;
264 if ( !mayHaveBackrefs
)
266 textNew
= replacement
;
269 // the position where we start looking for the match
271 // NB: initial version had a nasty bug because it used a wxChar* instead of
272 // an index but the problem is that replace() in the loop invalidates
273 // all pointers into the string so we have to use indices instead
274 size_t matchStart
= 0;
276 // number of replacement made: we won't make more than maxMatches of them
277 // (unless maxMatches is 0 which doesn't limit the number of replacements)
278 size_t countRepl
= 0;
280 // note that "^" shouldn't match after the first call to Matches() so we
281 // use wxRE_NOTBOL to prevent it from happening
282 while ( (!maxMatches
|| countRepl
< maxMatches
) &&
283 Matches(text
->c_str() + matchStart
, countRepl
? wxRE_NOTBOL
: 0) )
285 // the string possibly contains back references: we need to calculate
286 // the replacement text anew after each match
287 if ( mayHaveBackrefs
)
289 mayHaveBackrefs
= FALSE
;
291 textNew
.reserve(replacement
.length());
293 for ( const wxChar
*p
= replacement
.c_str(); *p
; p
++ )
295 size_t index
= (size_t)-1;
297 if ( *p
== _T('\\') )
299 if ( wxIsdigit(*++p
) )
303 index
= (size_t)wxStrtoul(p
, &end
, 10);
304 p
= end
- 1; // -1 to compensate for p++ in the loop
306 //else: backslash used as escape character
308 else if ( *p
== _T('&') )
310 // treat this as "\0" for compatbility with ed and such
314 // do we have a back reference?
315 if ( index
!= (size_t)-1 )
319 if ( !GetMatch(&start
, &len
, index
) )
321 // we can't do it because GetMatch() returns FALSE
322 // even for a valid back reference index if it didn't
323 // match for this expression (e.g. it when alternative
324 // branches were used and the one contained the back
327 // it would be better to distinguish between this case
328 // and really invalid index, but I don't know how to
331 //wxFAIL_MSG( _T("invalid back reference") );
337 textNew
+= wxString(text
->c_str() + matchStart
+ start
,
340 mayHaveBackrefs
= TRUE
;
343 else // ordinary character
351 if ( !GetMatch(&start
, &len
) )
353 // we did have match as Matches() returned true above!
354 wxFAIL_MSG( _T("internal logic error in wxRegEx::Replace") );
360 text
->replace(matchStart
, len
, textNew
);
364 matchStart
+= textNew
.length();
370 // ----------------------------------------------------------------------------
371 // wxRegEx: all methods are mostly forwarded to wxRegExImpl
372 // ----------------------------------------------------------------------------
385 bool wxRegEx::Compile(const wxString
& expr
, int flags
)
389 m_impl
= new wxRegExImpl
;
392 if ( !m_impl
->Compile(expr
, flags
) )
394 // error message already given in wxRegExImpl::Compile
404 bool wxRegEx::Matches(const wxChar
*str
, int flags
) const
406 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
408 return m_impl
->Matches(str
, flags
);
411 bool wxRegEx::GetMatch(size_t *start
, size_t *len
, size_t index
) const
413 wxCHECK_MSG( IsValid(), FALSE
, _T("must successfully Compile() first") );
415 return m_impl
->GetMatch(start
, len
, index
);
418 wxString
wxRegEx::GetMatch(const wxString
& text
, size_t index
) const
421 if ( !GetMatch(&start
, &len
, index
) )
422 return wxEmptyString
;
424 return text
.Mid(start
, len
);
427 int wxRegEx::Replace(wxString
*pattern
,
428 const wxString
& replacement
,
429 size_t maxMatches
) const
431 wxCHECK_MSG( IsValid(), -1, _T("must successfully Compile() first") );
433 return m_impl
->Replace(pattern
, replacement
, maxMatches
);
436 #endif // wxUSE_REGEX