Partilhar via


Performing Culture-Insensitive Operations in the RegularExpressions Namespace 

Methods in the System.Text.RegularExpressions namespace use the Thread.CurrentCulture property to perform operations that you specify as case-insensitive. As a result, case-insensitive operations in the RegularExpressions namespace are culture-sensitive by default. For example, the Regex Class provides a constructor that allows you to initialize a new instance specifying an options parameter. The options parameter is a bitwise OR combination of RegexOptions Enumeration values. The RegexOptions enumeration contains an IgnoreCase member that specifies case-insensitive matching. When you pass IgnoreCase as part of the options parameter to the Regex constructor, matching is case-insensitive and culture-sensitive.

To obtain culture-insensitive behavior from methods in the RegularExpressions namespace, pass the RegexOptions enumeration's CultureInvariant member as part of the options parameter to the Regex constructor. The following example demonstrates how to create a Regex that is case-insensitive and culture-insensitive.

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

This code produces the following output, verifying that a case-insensitive Regex.IsMatch of the strings "i" and "I" returns true for the InvariantCulture.

The result of the match is: True

See Also

Reference

System.Text.RegularExpressions Namespace

Other Resources

Performing Culture-Insensitive String Operations
Regular Expression Language Elements