我有一个方法,它有一个 if 语句,它会在找到特殊字符时进行捕获。如果找到特殊字符的位置并将其替换为_A,我现在想做什么

一些例子

  • test# 变成 test_A
  • I#hope#someone#knows#the#answer# 变成 I_Ahope_Asomeone_Aknows_Athe_Aanswer_A

  • 或者如果它有多个特殊字符
  • You?didnt#understand{my?Question# 变成 You_Adidnt_Aunderstand_Amy_AQuestion_A

  • 我是否必须遍历整个字符串,当我到达该字符时将其更改为 _A 还是有更快的方法?

    最佳答案

    # 与其他任何字符一样,您可以使用 -replace 运算符:

    PS C:\>'I#hope#someone#knows#the#answer#' -replace '#','_A'
    I_Ahope_Asomeone_Aknows_Athe_Aanswer_A
    

    正则表达式很神奇,你可以定义所有你喜欢的特殊情况(大括号必须被转义):
    PS C:\>'You?didnt#understand{my?Question#' -replace '[#?\{]','_A'
    You_Adidnt_Aunderstand_Amy_AQuestion_A
    

    所以你的函数可能看起来像这样:

    function Replace-SpecialChars {
        param($InputString)
    
        $SpecialChars = '[#?\{\[\(\)\]\}]'
        $Replacement  = '_A'
    
        $InputString -replace $SpecialChars,$Replacement
    }
    
    Replace-SpecialChars -InputString 'You?didnt#write{a]very[good?Question#'
    

    如果您不确定要转义哪些字符,请让 regex 类为您完成!

    function Replace-SpecialChars {
        param(
            [string]$InputString,
            [string]$Replacement  = "_A",
            [string]$SpecialChars = "#?()[]{}"
        )
    
        $rePattern = ($SpecialChars.ToCharArray() |ForEach-Object { [regex]::Escape($_) }) -join "|"
    
        $InputString -replace $rePattern,$Replacement
    }
    

    或者,您可以使用 .NET 字符串方法 Replace() :
    'You?didnt#understand{my?Question#'.Replace('#','_A').Replace('?','_A').Replace('{','_A')
    

    但我觉得正则表达式的方式更简洁

    关于powershell - 查找和替换特殊字符powershell,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30778098/

    10-11 02:15
    查看更多