Introductory Examples Using Regular Expressions
You can use a regular expression to return a substring; for example, here's how you might match all Windows messages (prefix WM_):
#include <rw/cstring.h>
#include <rw/tools/regex.h> // Get access to RWTRegex<T>
#include <iostream>
using std::cout;
using std::endl;
 
int main()
{
RWCString a(“A message named WM_CREATE”);
// Construct a Regular Expression to match Windows messages:
RWTRegex<char> re(“WM_[A-Z]*”);
RWTRegexResult<char>result;
if (result=re.search(a))
cout << result.subString(a) << endl;
else
cout << “No match in” << a << endl;
return 0;
}
Program Output:
WM_CREATE
The search method on RWTRegex determines if there is a match. Then the RWTRegexResult::substring() method obtains a matched string. The following example shows some of the capabilities of extended regular expressions:
 
#include <rw/cstring.h>
#include <rw/tools/regex.h> // Get access regular expressions
#include <iostream>
using std::cout;
using std::endl;
 
int main()
{
RWTRegex<char> re("Lisa|Betty|Eliza");
RWCString s("Betty II is the Queen of England.");
// Replace first occurrence of "Lisa" or "Betty" or "Eliza"
// with "Elizabeth"
re.replace(s, "Elizabeth");
cout << s << endl;
 
s = "Leg Leg Hurrah!";
re = RWTRegex<char>("Leg");
 
// Replace all occurrences of "Leg" with "Hip"
re.replace(s, "Hip", 0);
cout << s << endl;
return 0;
}
Program Output:
Elizabeth II is the Queen of England.
Hip Hip Hurrah!