I recently had to perform some string replacements in .net and found myself developing a regular expression replacement function for this purpose. After getting it to work I
This is a VB.NET adaptation of rboarman's answer above with the necessary checks for null and empty strings to avoid an infinite loop.
Public Function Replace(ByVal originalString As String,
ByVal oldValue As String,
ByVal newValue As String,
ByVal comparisonType As StringComparison) As String
If Not String.IsNullOrEmpty(originalString) AndAlso
Not String.IsNullOrEmpty(oldValue) AndAlso
newValue IsNot Nothing Then
Dim startIndex As Int32
Do While True
startIndex = originalString.IndexOf(oldValue, startIndex, comparisonType)
If startIndex = -1 Then Exit Do
originalString = originalString.Substring(0, startIndex) & newValue &
originalString.Substring(startIndex + oldValue.Length)
startIndex += newValue.Length
Loop
End If
Return originalString
End Function
This is natively available in .NET Core 2.0+ with String.Replace which has the following overloads
public string Replace (string oldValue, string newValue, StringComparison comparisonType);
public string Replace (string oldValue, string newValue, bool ignoreCase, System.Globalization.CultureInfo culture);
So you can use either like this:
"A".Replace("a", "b", StringComparison.CurrentCultureIgnoreCase);
"A".Replace("a", "b", true, CultureInfo.CurrentCulture);
PS: You can browse .NET Core source if you want to see how MS implemented it
Visual Basic has an Option Compare setting which can be set to Binary
or Text
Setting to Text
will make all string comparisons across your project case insensitive by default.
So, as other answers have suggested, if you are pulling in the Microsoft.VisualBasic.dll
, when calling Strings.Replace if you don't explicitly pass a CompareMethod the method will actually defer to the Compare option for your file or project using the [OptionCompare]
Parameter Attribute
So either of the following will also work (top option only available in VB , but both rely on VisualBasic.dll)
Option Compare Text
Replace("A","a","b")
Replace("A","a","b", Compare := CompareMethod.Text)
You can use Microsoft.VisualBasic.Strings.Replace and pass in Microsoft.VisualBasic.CompareMethod.Text
to do a case insensitive replace like this:
Dim myString As String = "One Two Three"
myString = Replace(myString, "two", "TWO", Compare:= CompareMethod.Text)