OVERVIEW
Regular expressions is a very complex subject and it is used in a lot of languages. We cannot go into the details of how regular expressions work, but for the sake of this tutorial series, we can say that wxWidgets supports regular expressions and we can use them for string parsing and extraction. The wxRegEx class is the main class which handles regular expressions.
We have two sample codes below. The first one extracts any string that is all capital letters from a sample text. The second one is a little more complex and extracts integers from a text repeatedly unless it cannot find any.
SAMPLE CODE
regexpsimple.cpp
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/regex.h>
#include <wx/string.h>
int main(int argc, char**argv) {
wxInitialize();
wxString pattern = wxT("([A-Z]+)");
wxRegEx *regExp = new wxRegEx(pattern);
wxString text = wxT("some of THIS text is in capitals");
wxPuts(text);
bool result = regExp->Compile(pattern);
if (!result) {
wxPuts("Compile failed");
return -1;
}
if (regExp->Matches(text)) {
wxPrintf(wxT("Match=%s\n"),regExp->GetMatch(text, 0));
}
delete regExp;
wxPuts(wxT("done"));
wxUninitialize();
}
The output is given below
regexp.cpp
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/regex.h>
#include <wx/string.h>
int main(int argc, char**argv) {
wxInitialize();
wxString pattern = wxT("([0-9]+)");
wxRegEx *regExpNumber = new wxRegEx(pattern);
wxString text = wxT("this is a text 1817,128128 some words 32withtext6124.word09");
wxPuts(text);
bool result = regExpNumber->Compile(pattern);
if (!result) {
wxPuts("Compile failed");
return -1;
}
if (regExpNumber->Matches(text)) {
wxPuts("Matches are there");
size_t index = 0;
size_t len = 0;
size_t start = 0;
while(regExpNumber->GetMatch(&start, &len, 0)) {
wxPrintf(wxT("Match=%s\n"),regExpNumber->GetMatch(text, 0));
index = start+len;
text = text.Mid(index);
wxPuts(text);
if (!regExpNumber->Matches(text)) {
break;
}
}
}
delete regExpNumber;
wxPuts(wxT("done"));
wxUninitialize();
}
The output is shown below
Leave a Reply