【问题标题】:Returning matching characters from a string array in powershell从powershell中的字符串数组中返回匹配的字符
【发布时间】:2021-12-07 11:43:39
【问题描述】:

我在一些可能很简单的事情上遇到了困难。 本质上,我想返回数组中字符的任何实例,我的示例应该比这个解释更清楚。需要注意的一件事是,我将在循环中执行此操作,并且索引不会相同,所讨论的字母也不会相同,因此据我所知,我无法使用 .indexof 或子字符串;

$array = "asdfsdgfdshghfdsf"
$array -match "d"

返回:真

我希望它返回什么:ddd

类似于 bash 中的 grep

【问题讨论】:

    标签: powershell powershell-5.1


    【解决方案1】:

    您可以使用-replace 运算符来删除不是 d 的任何内容:

    PS ~> $string = "asdfsdgfdshghfdsf"
    PS ~> $string -replace '[^d]'
    dddd
    

    请注意,PowerShell 中的所有字符串运算符默认情况下都in区分大小写,请使用-creplace 进行区分大小写的替换:

    PS ~> $string = "abcdABCD"
    PS ~> $string -replace '[^d]'
    dD
    PS ~> $string -creplace '[^d]'
    d
    

    您可以从这样的字符串生成否定字符类模式:

    # define a string with all the characters
    $allowedCharacters = 'abc'
    
    # generate a regex pattern of the form `[^<char1><char2><char3>...]`
    $pattern = '[^{0}]' -f $allowedCharacters.ToCharArray().ForEach({[regex]::Escape("$_")})
    

    然后像以前一样使用-replace(或-creplace):

    PS ~> 'abcdefgabcdefg' -replace $pattern
    abcabc
    

    【讨论】:

      【解决方案2】:

      使用 select-string -allmatches,匹配对象数组将包含所有匹配项。 -join 正在将匹配项转换为字符串。

      $array = 'asdfsdgfdshghfdsf'
      -join ($array | select-string d -AllMatches | % matches)
      
      dddd
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-26
        • 1970-01-01
        • 1970-01-01
        • 2019-09-03
        • 1970-01-01
        • 2018-02-28
        • 2020-08-07
        • 2020-12-03
        相关资源
        最近更新 更多