How to: Use Regular Expressions to Validate Data Formatting (C++/CLI)


The new home for Visual Studio documentation is Visual Studio 2017 Documentation on

The latest version of this topic can be found at Use Regular Expressions to Validate Formatting (C++/CLI).

The following code example demonstrates the use of regular expressions to verify the formatting of a string. In the following code example, the string should contain a valid phone number. The following code example uses the string "\d{3}-\d{3}-\d{4}" to indicate that each field represents a valid phone number. The "d" in the string indicates a digit, and the argument after each "d" indicates the number of digits that must be present. In this case, the number is required to be separated by dashes.

// regex_validate.cpp  
// compile with: /clr  
#using <System.dll>  
using namespace System;  
using namespace Text::RegularExpressions;  
int main()  
   array<String^>^ number =   
   String^ regStr = "^\\d{3}-\\d{3}-\\d{4}$";  
   for ( int i = 0; i < number->Length; i++ )  
      Console::Write( "{0,14}", number[i] );  
      if ( Regex::IsMatch( number[i], regStr ) )  
         Console::WriteLine(" - valid");  
         Console::WriteLine(" - invalid");  
   return 0;  

.NET Framework Regular Expressions
.NET Programming with C++/CLI (Visual C++)