Invariant String Replace Function

S-Soft 666 Reputation points
2023-02-17T20:34:09.2466667+00:00

Hi,

I've found this code to use as a case insensitive string replace:

Dim MyIndex As Integer = InputString.IndexOf(FindString, StringComparison.OrdinalIgnoreCase)

Dim MyMatch As Boolean = MyIndex >= 0

If MyMatch = True Then

StringReplaceInvariant = StringReplaceInvariant.Remove(MyIndex, FindString.Length)

StringReplaceInvariant = StringReplaceInvariant.Insert(MyIndex, ReplaceString)

End If

But not exactly like .NET String.Replace, as it only replace the first occurrence, any idea how to change it to replace all occurrences?

Thanks for advise :)

Developer technologies | VB
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. LesHay 7,141 Reputation points
    2023-02-19T12:39:10.6+00:00

    Hi

    No apologies needed, on re-reading my comment, it comes over as a bit harsh which was not intended. I just meant that I too am not an expert (despite the MS labels in the forum)

    If you want to process a bunch of items, the best way is to loop through the collection (List, Array etc) and check/replace for each item. There is likely a LINQ way to do it too but that is a whole new topic.

    Regex (and LINQ) is generally slower, but in this case, without having to write a bunch of code, Regex is appropriate. I only ever use Regex when forced to (and then, I turn to the forum for help too)

    Anyway, try this out: it loops through one list and fills the second list with amended strings.

        Dim MyStrings1 As New List(Of String)({"Input (StRinGs)", "(StRiNgS)", "(Text)"})
        Dim MyStrings2 As New List(Of String)
    
        For Each s As String In MyStrings1
          MyStrings2.Add(Regex.Replace(s, "\(StRiNgS\)", "(Text)", RegexOptions.IgnoreCase))
        Next
    
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. LesHay 7,141 Reputation points
    2023-02-17T22:01:27.9833333+00:00

    Hi

    This example does it.

    Option Strict On
    Option Explicit On
    Imports System.Text.RegularExpressions
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        Dim startString As String = "atyAuopadfgAwww"
        Dim result As String = Regex.Replace(startString, "a", "X", RegexOptions.IgnoreCase)
    
        Stop
    
      End Sub
    End Class
    
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.