Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
 Performing Culture-Insensitive Oper...
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Developer's Guide
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.

Visual Basic
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
C#
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
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement | Site Feedback
Page view tracker