Click here to Skip to main content
Click here to Skip to main content

Use regular expression in your C++ program

By , 25 Jan 2001
 

Introduction

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 http://msdn.microsoft.com/scripting/default.htm?/scripting/vbscript/doc/vsobjregexp.htm. 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);
            value.ReleaseBuffer();

			//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() )
					{
						return;
					}
				}
			}
			CString strMsg = CString("The input does not exactly have the pattern ") + lpszPattern;
			pDX->m_pDlgWnd->MessageBox(strMsg);
			pDX->PrepareEditCtrl(nIDC);
			pDX->Fail();
      }
      else
      {
      }
	}
	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.

License

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
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralIRegExpPtr : undeclared identifiermemberajitatif angajetor26 Jan '09 - 0:40 
GeneralRe: IRegExpPtr : undeclared identifier [modified]memberAndreBroz14 Jul '09 - 2:28 
GeneralRe: IRegExpPtr : undeclared identifiermemberineox24 Mar '10 - 2:40 
GeneralGlobal p arameter won't work (for me)memberarkyc6 May '03 - 17:37 
GeneralRe: Global p arameter won't work (for me)memberarkyc6 May '03 - 17:43 
GeneralRe: Global p arameter won't work (for me)memberAndreBroz14 Jul '09 - 2:18 
QuestionHow can i know all the members of these class! What form they are?memberDavidlou13 Mar '02 - 7:18 
QuestionHow to Uninitialize ObjectmemberNIrving18 Nov '01 - 0:01 
Hi all,
When I try to Uninitialize the object it core dumps. Does anybody know how I can unreference the reference I have created, as I would like to use this without crashing the app.
 
==n
AnswerRe: How to Uninitialize ObjectmemberPhilip Patrick31 Jan '02 - 7:57 
AnswerRe: How to Uninitialize ObjectmemberMatt Fitzgerald14 Feb '02 - 13:16 
GeneralregexmemberTomaz Stih4 Mar '01 - 23:45 
GeneralRe: regexmemberlorenzo4 Jan '02 - 3:27 
GeneralAbout the type library...sussPatrick Dell'Era21 Oct '00 - 11:00 
GeneralRe: About the type library... [modified]memberAndreBroz13 Jul '09 - 21:42 
GeneralSome detailssussRoberto Guerzoni17 Oct '00 - 5:50 
GeneralRe: Some detailssussSherwood Hu17 Oct '00 - 6:51 
GeneralThis macro is no longer neededsussSherwood Hu17 Oct '00 - 7:46 
GeneralRe: This macro is no longer neededsussRoberto Guerzoni18 Oct '00 - 2:06 
GeneralRe: This macro is no longer neededsussOtis B18 Oct '00 - 5:51 
GeneralThe solutionsussSherwood Hu18 Oct '00 - 6:50 
GeneralProblem with USES_CONVERSIONsussRoberto Guerzoni16 Oct '00 - 22:18 
GeneralRe: Problem with USES_CONVERSIONsussSimon Capewell16 Oct '00 - 23:41 
GeneralClever IdeasussUwe Keim16 Oct '00 - 20:01 
GeneralRe: Clever IdeasussWilliam E. Kempf17 Oct '00 - 7:02 
GeneralRe: Clever IdeasussUwe Keim17 Oct '00 - 20:26 
GeneralRe: Clever IdeamemberA. Reskala11 Jul '01 - 20:08 
GeneralRe: Clever IdeamemberTodd Smith12 Jul '01 - 5:10 

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

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