如何:使用正则表达式分析字符串 (C++/CLI)

下面的代码示例演示如何使用 System.Text.RegularExpressions 命名空间中的 Regex 类分析简单的字符串。 首先构造一个包含多种类型的字描绘器的字符串。 然后结合使用 Regex 类和 Match 类来分析该字符串。 然后,分别显示句子中的每个字。

示例

// 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;
}

请参见

其他资源

.NET Framework 正则表达式

编程在Visual C++的.NET