Share via


在 RegularExpressions 命名空間中執行不區分文化特性作業

System.Text.RegularExpressions 命名空間中的方法使用 Thread.CurrentCulture 屬性,執行您指定為不區分大小寫的作業。因此,RegularExpressions 命名空間中的不區分大小寫作業預設為區分文化特性。例如,Regex 類別會提供建構函式,讓您可以初始化指定 options 參數的新執行個體。options 參數是 RegexOptions Enumeration 值的位元 OR 組合。RegexOptions 列舉型別 (Enumeration) 包含指定不區分大小寫比對的 IgnoreCase 成員。當您將 IgnoreCase 做為 options 參數的一部分傳遞至 Regex 建構函式時,其對應不區分大小寫但區分文化特性。

若要從 RegularExpressions 命名空間的方法取得不區分文化特性的行為,請將 RegexOptions 列舉型別的 CultureInvariant 成員做為 options 參數的一部分傳遞至 Regex 建構函式。下列範例示範如何建立不區分大小寫和不區分文化特性的 Regex

Imports System
Imports System.Globalization
Imports System.Text.RegularExpressions

Public Class CultureChange
    Public Shared Sub Main()
      ' Perform a case-insensitive, culture-insensitive
      ' Regex operation.
      Dim TestString As String = "i"
      Dim r As New Regex("I", RegexOptions.IgnoreCase Or _
                   RegexOptions.CultureInvariant)
      Dim result As Boolean = r.IsMatch(TestString)
      Console.WriteLine("The result of the comparison is: {0}", result)
   End Sub
End Class
using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class CultureChange
{
   public static void Main() 
   {
      // Perform the case-insensitive, culture-insensitive 
      // Regex operation.
      String TestString = "i";
      Regex r = new Regex("I", RegexOptions.IgnoreCase | 
                RegexOptions.CultureInvariant);
      bool result = r.IsMatch(TestString);
      Console.WriteLine("The result of the comparison is: {0}",
                         result); 
   }
}

這個程式碼會產生下列輸出,並證實字串 "i" 和 "I" 不區分大小寫的 Regex.IsMatch 會對 InvariantCulture 傳回 true

The result of the match is: True

請參閱

參考

System.Text.RegularExpressions Namespace

其他資源

執行不區分文化特性的字串作業
規則運算式語言項目