Visual C++ in Short: Regular Expressions
ATL includes a lightweight regular expression implementation. Although originally part of Visual C++, it is now included with the ATL Server download.
The CAtlRegExp class template implements the parser and matching engine. Its single template argument specifies the character traits such as CAtlRECharTraitsW for Unicode and CAtlRECharTraitsA for ANSI. The template argument also has a default argument based on whether or not _UNICODE is defined.
The CAtlREMatchContext class template provides an array of match groups for a successful match of a regular expression. It has the same default template argument as CAtlRegExp.
In the example below, CAtlRegExp’s Parse method is used to convert the regular expression into an instruction stream that is then used by the Match method to efficiently match the input string. Each match group is defined by a start and end pointer, defining the range of characters so that a copy does not have to be made if it is not needed.
The regular expression grammar is defined at the top of the atlrx.h header file.
#include <atlrx.h>
#include <atlstr.h>
#define ASSERT ATLASSERT
int main()
{
CAtlRegExp<> regex;
const REParseError status = regex.Parse(L"^/blog/{\\d\\d\\d\\d}/{\\d\\d?}/{\\d\\d?}/{\\a+}$");
ASSERT(REPARSE_ERROR_OK == status);
CAtlREMatchContext<> match;
if (regex.Match(L"/blog/2008/7/16/SomePost", &match))
{
ASSERT(4 == match.m_uNumGroups);
PCWSTR start = 0;
PCWSTR end = 0;
match.GetMatch(0, &start, &end);
const UINT year = _wtoi(start);
match.GetMatch(1, &start, &end);
const UINT month = _wtoi(start);
match.GetMatch(2, &start, &end);
const UINT day = _wtoi(start);
match.GetMatch(3, &start, &end);
const CString name(start, end - start);
wprintf(L"Year: %d\n", year);
wprintf(L"Month: %d\n", month);
wprintf(L"Day: %d\n", day);
wprintf(L"Name: %s\n", name);
}
}
If you’re looking for one of my previous articles here is a complete list of them for you to browse through.
Produce the highest quality screenshots with the least amount of effort! Use Window Clippings.