Searching, parsing, and validating text input is always a big part of contemporary programming. Regular expression is a powerful tool that is available to C#, Java, Perl, ... Unfortunately, it does not come with C++ or MFC library. One of the best regular expression library in C++ is Boost.Regex, which is accepted as part of C++ standard library in the next release of C++ standard. Boost.Regex library provides direct support for MFC/ATL string types, so that integration with MFC/ATL project is very straightforward. However, integrating BOOST library into Visual Studio 6.0 or older is very hard, due to their lack of standard C++ support.
To use Boost.Regex in a MFC/ATL project in Visual Studio 2003 or above is very easy. Just follow these steps:
- Download installation package created by Boost Consulting, following the links: Products > Free Downloads, you will find installer for latest BOOST library distribution. Just run the installer, it will automatically download the selected BOOST library source code from a and pre-compiled binaries from a mirror site;
- Setup VC++ include and library directories for BOOST libraries, detailed instructions can be found here: BOOST--Getting Started on Windows;
- If you are like me, getting very comfortable using MFC/ATL string types like
CString, CStringW, TCHAR, _T, ...Please notice BOOST libraries normally only support standard string type. Please read this before you start to write code: Boost.Regex--Working with MFC/ATL String Types. Boost.Regex does provide a set of overloaded functions that use MFC/ATL types, you will need to include a header file: <boost\regex\mfc.hpp> which defines all the overloaded Boost.Regex APIs as shown in the document;
1://boost regular expression library
3://support for MFC string types in boost Regular Expression library
6://extract string value from XML by given key
7://Example: given the string below, and key="LogFile"
8://<add key="LogFile" value="c:\temp\error.txt" />
9://return will be: c:\temp\error.txt
10:CString GetXMLValue(LPCTSTR xmlContent, LPCTSTR key)
12: CString strRegEx;
13: strRegEx.Format("<add\\s+key\\s*=\\s*\"%s\"\\s+value\\s*=\\s*\"([^\"]*)\"\\s*/>", key);
14: tregex re(strRegEx);
15: tmatch matches;
17: //we are expecting no more than 1 match in the file
18: if(regex_search(xmlContent, matches, re))
20: //extract the value from sub-expression
21: return CString(matches.first, matches.length());
25: return "";
Static link to Boost.Regex library for the above sample code, adds about 80K to the compiled binary output.
Official documentation of Boost.Regex library: http://www.boost.org/libs/regex/doc/index.htm.