代码之家  ›  专栏  ›  技术社区  ›  Icarus

PowerShell字符串匹配的奇怪行为

  •  -1
  • Icarus  · 技术社区  · 7 年前

    当我在PowerShell中写这篇文章时,

    $Person ="Guy Thomas 1949bhau"
    $Person -Match "19?9"
    

    它返回true。

    但当我在PowerShell中写这篇文章时,

    $Person ="Guy Thomas 1949bhau"
    $Person -Match "19?9bhau"
    

    它返回false。

    这种奇怪行为的原因是什么?首先,它是如何回归真实的?

    2 回复  |  直到 6 年前
        1
  •  0
  •   Ansgar Wiechers    7 年前

    这种行为一点也不奇怪。这个 -match operator regular expression 比赛。在正则表达式中 ? 是一个特殊字符,其含义为“前一表达式的零倍或更多倍”。因此是一个(正则)表达式 19?9 表示“一个后跟零个或多个9和另一个9”(匹配 19 , 199 , 1999 , 19999 等)。要精确匹配需要使用的任意字符 . . 但是,在您的情况下,可能需要匹配一个数字( \d [0-9] )而不仅仅是任何角色。

    如果要使用通配符匹配(其中 ? 表示“任何单个字符”,以及 * 表示“零个或多个字符”),您需要使用 -like 操作人员不过,要注意 -匹配 运算符匹配字符串中的任何位置的模式(除非模式被锚定),则 -喜欢 除非您将 * 在图案的开头和/或结尾。 -like '19?9' 匹配例如“1979”和“19m9”,但不匹配“a1979”或“1979a”。你需要 -like '*19?9*' 为此。

        2
  •  0
  •   postanote    7 年前

    或者这些选项。。。

    $Person ="Guy Thomas 1949bhau"
    $Pattern = '19?.*9'
    (((Select-String -InputObject $Person -Pattern $Pattern -AllMatches).Matches).Value)
    
    Results
    
    1949
    
    $Person ="Guy Thomas 1949bhau"
    $Pattern = '19?.*9*'
    (((Select-String -InputObject $Person -Pattern $Pattern -AllMatches).Matches).Value)
    
    Resutls 
    
    1949bhau
    

    [regex]::Matches($Person,$Pattern)
    
    Results 
    
    Groups   : {0}
    Success  : True
    Name     : 0
    Captures : {0}
    Index    : 11
    Length   : 8
    Value    : 1949bhau
    

    [regex]::Matches($Person,$Pattern).Value
    
    Results
    
    1949bhau