How to replace string case insensitive?

Welcome Forums General PowerShell Q&A How to replace string case insensitive?

  • This topic has 3 replies, 3 voices, and was last updated 1 month ago by
    js
    Participant
    .
Viewing 3 reply threads
  • Author
    Posts
    • #199949
      Participant
      Topics: 1
      Replies: 2
      Points: 22
      Rank: Member

      Hello,

      how would I do case-insensitive string replacing?

      <!–StartFragment –>

      `Desktop> ‘aaa’.Replace(‘aaa’, ‘bbb’, ‘OrdinalIgnoreCase’)`
      `Cannot find an overload for “Replace” and the argument count: “3”.`
      `At line:1 char:1`
      `+ ‘aaa’.Replace(‘aaa’, ‘bbb’, ‘OrdinalIgnoreCase’)`
      `+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
      `+ CategoryInfo : NotSpecified: (:) [], MethodException`
      `+ FullyQualifiedErrorId : MethodCountCouldNotFindBest`
      in C# the code works:
      `foreach (string badString in badStrings)`
      `    fileName = fileName.Replace($”.{badString}.”, “.”, StringComparison.OrdinalIgnoreCase);`
      edit:
      I found this workaround:
      `    foreach ($badString in $badStrings)`
      `    {`
      `        $badString = [Regex]::Escape($badString)`
      `        $fileName = $fileName -replace (‘\.’ + $badString + ‘\.’), ‘.’`
      `    }`

      <!–EndFragment –>

      • This topic was modified 1 month ago by stax76.
      • This topic was modified 1 month ago by stax76.
      • This topic was modified 1 month ago by stax76.
      • This topic was modified 1 month ago by stax76.
    • #199967
      Participant
      Topics: 5
      Replies: 296
      Points: 273
      Helping Hand
      Rank: Contributor
      # Case-Insensitive
      PS> 'AAAaaaBBBCDeFg' -replace 'a','*'
      ******BBBCDeFg
      # Case-Sensitive
      PS> 'AAAaaaBBBCDeFg' -creplace 'a','*'
      AAA***BBBCDeFg
      
    • #199970
      Participant
      Topics: 1
      Replies: 2
      Points: 22
      Rank: Member

      Thanks for the reply, the -replace operator uses regex which is problematic because my input strings might contain regex syntax.

      I found my problem finally, my C# code is .NET Core based and apparently this overload does not exist in .NET Framework based PowerShell. I can use [Regex]::Escape to escape my input strings.

      • This reply was modified 1 month ago by stax76.
    • #200015
      js
      Participant
      Topics: 28
      Replies: 760
      Points: 2,140
      Helping Hand
      Rank: Community Hero
      'Hi'.replace('h','i')
      Hi
      
      'Hi'.replace('H','i')
      ii
      
      'hi'.replace('.','j')
      hi
      
Viewing 3 reply threads
  • You must be logged in to reply to this topic.