Click here to Skip to main content
13,289,626 members (57,665 online)
Click here to Skip to main content
Add your own
alternative version


20 bookmarked
Posted 15 Oct 2000

Use regular expression in your C++ program

, 25 Jan 2001
Rate this:
Please Sign up or sign in to vote.
how to use the Microsoft regular expression object in your C++ program
<!-- Add the rest of your HTML here -->


Regular expression provides a convenient way to specify complicated string pattern for search, replace or validate the text input. Since it is very useful, many people wrote their own library. Many libraries I found are buggy and it takes a lot of time to debug source code. However, actually you do not need to search any more, since there is already one built in your computer for free – the regular expression parser written by Microsoft.

As many other utilities, Microsoft provides this functionality using COM interface. It is easy to find this COM server object, named Microsoft VBScript Regular Expressions 5.5, with the tool oleview:

One problem is that there is no type library associated with this DLL. Fortunately it is not a big deal since we have the IDL definition. From OleView, save the IDL definition into a file and use MIDL to compile it, you will get type library. After that, we can use this type library within our C++ program. Suppose we have this file named RegExp.tlb.

use regular expression

You can find all the documentation in either MSDN or the URL Though it is for scripting, you can still use them directly with the help of the newly-added keyword #import since Visual C++ 6. Generally you define a pattern, then you can test this pattern against the input string. or exacute to see whether they are any matches.

To demonstrate its usage, we wrote a custome DDX routine to verify the input of a control in a dialog. The function prototype is listed as following:

void WINAPI DDX_RegExp(CDataExchange* pDX, int nIDC, LPCTSTR lpszPattern, CString& value);

If the control input exactly matches the specified pattern(lpszPattern), the validation is passed otherwise an message box will pop up.

#import "RegExp.tlb" no_namespace
void AFXAPI DDX_RegExp(CDataExchange* pDX, int nIDC, LPCTSTR lpszPattern, CString& value)
	try {
	static IRegExpPtr regExp( __uuidof(RegExp) );
	regExp->Pattern = _bstr_t(lpszPattern);
     HWND hWndCtrl = pDX->PrepareEditCtrl(nIDC);
      if (pDX->m_bSaveAndValidate)
            int nLen = ::GetWindowTextLength(hWndCtrl);
            ::GetWindowText(hWndCtrl, value.GetBufferSetLength(nLen),nLen+1);

			//now we verify it
			if ( regExp->Test( (LPCTSTR)value) )
				IMatchCollectionPtr matches=regExp->Execute((LPCTSTR)value);
				if ( matches->Count== 1)
					IMatchPtr match = matches->Item[0];
					if ( match->FirstIndex==0 && match->Length == value.GetLength() )
			CString strMsg = CString("The input does not exactly have the pattern ") + lpszPattern;
	catch (_com_error& e)
		AfxMessageBox( e.ErrorMessage() );

In the code above, we first use Test method to see whether there is a match. If there is one, we use Execute method to retrieve all the matches. There should be only one match.

After we define that, we can use this function in our MFC application. Note that you must initialize the COM library first in your application. The following will validate an input box to see if it matches the phone number format:

DDX_RegExp(pDX, IDC_INPUT, _T("\\d{3}-\\d{3}-\\d{4}"), m_strInput);

In this way, you can write validation code for more complicated pattern. The COM makes things a lot easier.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Sherwood Hu
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralIRegExpPtr : undeclared identifier Pin
ajitatif angajetor26-Jan-09 1:40
memberajitatif angajetor26-Jan-09 1:40 
GeneralRe: IRegExpPtr : undeclared identifier [modified] Pin
AndreBroz14-Jul-09 3:28
memberAndreBroz14-Jul-09 3:28 
GeneralRe: IRegExpPtr : undeclared identifier Pin
ineox24-Mar-10 3:40
memberineox24-Mar-10 3:40 
GeneralGlobal p arameter won't work (for me) Pin
arkyc6-May-03 18:37
memberarkyc6-May-03 18:37 
Hi All,

I'm having problems with the Global parameter for the Replace method. Whatever I do, only the first instance
of the text I want to replace is replaced.

My code is below. The return value of the "replacetext" method is:
"hi there stupid person. you are funny another test" and not "hi there stupid person. you are stupid another test"
as I expected. Any help is appreciated. I thought setting the global parameter to true would replace
all instances of "funny" with "stupid". Am i misunderstanding something? Cry | :((

I am using the type library generated as a result of opening up vbscript as a resource and
expanding the "TYPELIB" branch, right clicking on the second typelib resource, select Export and then saving
the type library as RegExp.tlb.

It also doesn't work if i generate wrapper classes from the type library either instead of using the #import

Any help is appreciated. Wink | ;)

#import "regexp.tlb" named_guids no_namespace

CString replacetext(CString p_sText, CString p_sTextToReplace, CString p_sReplacementText, bool p_bReplaceAll)

CString l_strResult;


IRegExpPtr regExp( __uuidof(RegExp) );


if (p_bReplaceAll)

_bstr_t l_bstrReplace(p_sReplacementText);
_bstr_t l_bstrSource(p_sText);

BSTR l_bstrResult;


// regExp->Replace(l_bstrSource, l_bstrReplace, &l_bstrResult);

l_bstrResult = regExp->Replace(l_bstrSource, l_bstrReplace);

_bstr_t l_bstrResult2(l_bstrResult);


catch (_com_error& e)
AfxMessageBox( e.ErrorMessage() );



void CTesterDlg::OnButton1()

CString l_strResult=replacetext("hi there funny person. you are funny another test", "funny", "stupid", true);

GeneralRe: Global p arameter won't work (for me) Pin
arkyc6-May-03 18:43
memberarkyc6-May-03 18:43 
GeneralRe: Global p arameter won't work (for me) Pin
AndreBroz14-Jul-09 3:18
memberAndreBroz14-Jul-09 3:18 
QuestionHow can i know all the members of these class! What form they are? Pin
Davidlou13-Mar-02 8:18
memberDavidlou13-Mar-02 8:18 
QuestionHow to Uninitialize Object Pin
NIrving18-Nov-01 1:01
memberNIrving18-Nov-01 1:01 
AnswerRe: How to Uninitialize Object Pin
Philip Patrick31-Jan-02 8:57
memberPhilip Patrick31-Jan-02 8:57 
AnswerRe: How to Uninitialize Object Pin
Matt Fitzgerald14-Feb-02 14:16
memberMatt Fitzgerald14-Feb-02 14:16 
Generalregex Pin
Tomaz Stih5-Mar-01 0:45
memberTomaz Stih5-Mar-01 0:45 
GeneralRe: regex Pin
lorenzo4-Jan-02 4:27
memberlorenzo4-Jan-02 4:27 
GeneralAbout the type library... Pin
Patrick Dell'Era21-Oct-00 12:00
sussPatrick Dell'Era21-Oct-00 12:00 
GeneralRe: About the type library... [modified] Pin
AndreBroz13-Jul-09 22:42
memberAndreBroz13-Jul-09 22:42 
GeneralSome details Pin
Roberto Guerzoni17-Oct-00 6:50
sussRoberto Guerzoni17-Oct-00 6:50 
GeneralRe: Some details Pin
Sherwood Hu17-Oct-00 7:51
sussSherwood Hu17-Oct-00 7:51 
GeneralThis macro is no longer needed Pin
Sherwood Hu17-Oct-00 8:46
sussSherwood Hu17-Oct-00 8:46 
GeneralRe: This macro is no longer needed Pin
Roberto Guerzoni18-Oct-00 3:06
sussRoberto Guerzoni18-Oct-00 3:06 
GeneralRe: This macro is no longer needed Pin
Otis B18-Oct-00 6:51
sussOtis B18-Oct-00 6:51 
GeneralThe solution Pin
Sherwood Hu18-Oct-00 7:50
sussSherwood Hu18-Oct-00 7:50 
GeneralProblem with USES_CONVERSION Pin
Roberto Guerzoni16-Oct-00 23:18
sussRoberto Guerzoni16-Oct-00 23:18 
GeneralRe: Problem with USES_CONVERSION Pin
Simon Capewell17-Oct-00 0:41
sussSimon Capewell17-Oct-00 0:41 
GeneralClever Idea Pin
Uwe Keim16-Oct-00 21:01
sussUwe Keim16-Oct-00 21:01 
GeneralRe: Clever Idea Pin
William E. Kempf17-Oct-00 8:02
sussWilliam E. Kempf17-Oct-00 8:02 
GeneralRe: Clever Idea Pin
Uwe Keim17-Oct-00 21:26
sussUwe Keim17-Oct-00 21:26 
GeneralRe: Clever Idea Pin
A. Reskala11-Jul-01 21:08
memberA. Reskala11-Jul-01 21:08 
GeneralRe: Clever Idea Pin
Todd Smith12-Jul-01 6:10
memberTodd Smith12-Jul-01 6:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.171207.1 | Last Updated 26 Jan 2001
Article Copyright 2000 by Sherwood Hu
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid