共用方式為


規則運算式 (C++/CLI)

示範在 .NET Framework 中使用正則運算式類別的各種字串作業。

下列主題示範如何使用 .NET Framework System.Text.RegularExpressions 命名空間 (以及其中一種 System.String.Split 方法)來搜尋、剖析和修改字串。

使用正則運算式剖析字串

下列程式碼範例示範使用 Regex 命名空間中的 System.Text.RegularExpressions 類別進行簡單字串剖析。 建構包含多個字組描述項類型的字串。 接著會使用 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;
}

使用 Split 方法剖析字串

下列程式碼範例示範如何使用 System.String.Split 方法,從字串擷取每個單字。 會建構包含多個字分隔符號類型的字串,然後藉由使用 Split 描述項清單呼叫來剖析。 然後,句子中的每個字都會個別顯示。

範例

// regex_split.cpp
// compile with: /clr
using namespace System;

int main()
{
   String^ delimStr = " ,.:\t";
   Console::WriteLine( "delimiter : '{0}'", delimStr );
   array<Char>^ delimiter = delimStr->ToCharArray( );
   array<String^>^ words;
   String^ line = "one\ttwo three:four,five six seven";

   Console::WriteLine( "text : '{0}'", line );
   words = line->Split( delimiter );
   Console::WriteLine( "Number of Words : {0}", words->Length );
   for (int word=0; word<words->Length; word++)
      Console::WriteLine( "{0}", words[word] );

   return 0;
}

使用正則運算式進行簡單比對

下列程式碼範例會使用正則運算式來尋找確切的子字串相符專案。 搜尋是由靜態 IsMatch 方法執行,它會接受兩個字串做為輸入。 第一個是要搜尋的字串,第二個是要搜尋的模式。

範例

// regex_simple.cpp
// compile with: /clr
#using <System.dll>

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

int main()
{
   array<String^>^ sentence =
   {
      "cow over the moon",
      "Betsy the Cow",
      "cowering in the corner",
      "no match here"
   };

   String^ matchStr = "cow";
   for (int i=0; i<sentence->Length; i++)
   {
      Console::Write( "{0,24}", sentence[i] );
      if ( Regex::IsMatch( sentence[i], matchStr,
                     RegexOptions::IgnoreCase ) )
         Console::WriteLine("  (match for '{0}' found)", matchStr);
      else
         Console::WriteLine("");
   }
   return 0;
}

使用正則運算式來擷取資料欄位

下列程式碼範例示範使用正則運算式從格式化字串擷取資料。 下列程式碼範例會 Regex 使用 類別來指定對應至電子郵件地址的模式。 此分頁包含欄位識別碼,可用來擷取每個電子郵件地址的使用者和主機名稱部分。 類別 Match 可用來執行實際的模式比對。 如果指定的電子郵件地址有效,則會擷取並顯示使用者名稱和主機名稱。

範例

// Regex_extract.cpp
// compile with: /clr
#using <System.dll>

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

int main()
{
    array<String^>^ address=
    {
        "jay@southridgevideo.com",
        "barry@adatum.com",
        "treyresearch.net",
        "karen@proseware.com"
    };

    Regex^ emailregex = gcnew Regex("(?<user>[^@]+)@(?<host>.+)");

    for (int i=0; i<address->Length; i++)
    {
        Match^ m = emailregex->Match( address[i] );
        Console::Write("\n{0,25}", address[i]);

        if ( m->Success )
        {
            Console::Write("   User='{0}'",
            m->Groups["user"]->Value);
            Console::Write("   Host='{0}'",
            m->Groups["host"]->Value);
        }
        else
            Console::Write("   (invalid email address)");
        }

    Console::WriteLine("");
    return 0;
}

使用正則運算式重新排列資料

下列程式碼範例示範如何使用 .NET Framework 正則運算式支援來重新排列或重新格式化資料。 下列程式碼範例會使用 RegexMatch 類別,從字串擷取名字和姓氏,然後依反向順序顯示這些名稱元素。

類別 Regex 是用來建構描述資料目前格式的正則運算式。 假設這兩個名稱是以逗號分隔,而且可以在逗號周圍使用任意數量的空白字元。 然後,方法 Match 會用來分析每個字串。 如果成功,就會從 Match 物件擷取名字和姓氏並顯示。

範例

// regex_reorder.cpp
// compile with: /clr
#using <System.dll>
using namespace System;
using namespace Text::RegularExpressions;

int main()
{
   array<String^>^ name =
   {
      "Abolrous, Sam",
      "Berg,Matt",
      "Berry , Jo",
      "www.contoso.com"
   };

   Regex^ reg = gcnew Regex("(?<last>\\w*)\\s*,\\s*(?<first>\\w*)");

   for ( int i=0; i < name->Length; i++ )
   {
      Console::Write( "{0,-20}", name[i] );
      Match^ m = reg->Match( name[i] );
      if ( m->Success )
      {
         String^ first = m->Groups["first"]->Value;
         String^ last = m->Groups["last"]->Value;
         Console::WriteLine("{0} {1}", first, last);
      }
      else
         Console::WriteLine("(invalid)");
   }
   return 0;
}

下列程式碼範例示範如何使用正則運算式類別 Regex 來執行搜尋和取代。 這是使用 方法完成的 Replace 。 所使用的版本會接受兩個字串做為輸入:要修改的字串,以及要插入的字串取代符合提供給 Regex 物件的模式的區段(如果有的話)。

此程式碼會將字串中的所有數位取代為底線 (_),然後將那些數位取代為空字串,有效地移除它們。 相同的效果可以在單一步驟中完成,但此處會使用兩個步驟來進行示範。

範例

// regex_replace.cpp
// compile with: /clr
#using <System.dll>
using namespace System::Text::RegularExpressions;
using namespace System;

int main()
{
   String^ before = "The q43uick bro254wn f0ox ju4mped";
   Console::WriteLine("original  : {0}", before);

   Regex^ digitRegex = gcnew Regex("(?<digit>[0-9])");
   String^ after = digitRegex->Replace(before, "_");
   Console::WriteLine("1st regex : {0}", after);

   Regex^ underbarRegex = gcnew Regex("_");
   String^ after2 = underbarRegex->Replace(after, "");
   Console::WriteLine("2nd regex : {0}", after2);

   return 0;
}

使用正則運算式來驗證資料格式

下列程式碼範例示範如何使用正則運算式來驗證字串的格式。 在下列程式碼範例中,字串應該包含有效的電話號碼。 下列程式碼範例會使用字串 「\d-\d {3} -\d {3}{4} 」 來指出每個欄位都代表有效的電話號碼。 字串中的 「d」 表示數位,而每個 「d」 後面的引數表示必須存在的位數。 在此情況下,數位必須以破折號分隔。

範例

// regex_validate.cpp
// compile with: /clr
#using <System.dll>

using namespace System;
using namespace Text::RegularExpressions;

int main()
{
   array<String^>^ number =
   {
      "123-456-7890",
      "444-234-22450",
      "690-203-6578",
      "146-893-232",
      "146-839-2322",
      "4007-295-1111",
      "407-295-1111",
      "407-2-5555",
   };

   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");
      else
         Console::WriteLine(" - invalid");
   }
   return 0;
}

.NET Framework 規則運算式

另請參閱

以 C++/CLI 進行 .NET 程式設計 (Visual C++)