Export (0) Print
Expand All

How to: Parse Strings Using Regular Expressions 

The following code example demonstrates simple string parsing using the Regex class in the System.Text.RegularExpressions namespace. A string containing multiple types of word delineators is constructed. The string is then parsed using the Regex class in conjunction with the Match class. Then, each word in the sentence is displayed separately.

Example

// regex_parse.cpp
// compile with: /clr
#using <system.dll>

using namespace System;
using namespace System::Text::RegularExpressions;

int main( )
{
   int words = 0;
   String^ pattern = "[a-zA-Z]*";
   Console::WriteLine( "pattern : '{0}'", pattern );
   Regex^ regex = gcnew Regex( pattern );

   String^ line = "one\ttwo three:four,five six  seven";   
   Console::WriteLine( "text : '{0}'", line );
   for( Match^ match = regex->Match( line ); 
        match->Success; match = match->NextMatch( ) ) 
   {
      if( match->Value->Length > 0 )
      {
         words++;
         Console::WriteLine( "{0}", match->Value );
      }
   }
   Console::WriteLine( "Number of Words : {0}", words );

   return 0;
}

See Also

Community Additions

ADD
Show:
© 2014 Microsoft