在 RegularExpressions 命名空间中执行不区分区域性的操作

更新:2007 年 11 月

System.Text.RegularExpressions 命名空间中的方法使用 Thread.CurrentCulture 属性来执行您指定为不区分大小写的操作。因此,默认情况下,RegularExpressions 命名空间中不区分大小写的操作是区分区域性的。例如,Regex 类提供了构造函数,使您可以初始化指定 options 参数的新实例。options 参数是 RegexOptions 枚举值的按位“或”组合。RegexOptions 枚举包含 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.IsMatchInvariantCulture 返回 true

The result of the match is: True

请参见

参考

System.Text.RegularExpressions

其他资源

执行不区分区域性的字符串操作

正则表达式语言元素