HOW TO:使用規則運算式剖析字串

更新:2007 年 11 月

下列程式碼範例會示範使用 System.Text.RegularExpressions 命名空間的 Regex 類別 (Class) 進行簡單的字串剖析。範例會建構包含各種文字分隔符號的字串。接著搭配使用 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 規則運算式

.NET 程式設計指南