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

如何从这个字符串中获取日期?

  •  1
  • Rod  · 技术社区  · 2 年前

    PowerShell 5.1

    如何从这个字符串中获取日期?这些分隔符用起来很好吗?

    'blah blah ???5/28/24 15:55??? blah blah blah' -match '???.*\s.*???'
    $Matches
    

    我希望这能做到:

    -match '???.*\s.*???'

    1 回复  |  直到 2 年前
        1
  •  4
  •   Santiago Squarzon    2 年前

    你需要 escape 这个 ? 因为它是一个 special regex character (quantifier) ,我想你想要的是 \?\?\?.*\s.*\?\?\? 或简化 \?{3}.*\s.*\?{3} 如果你想捕捉 ??? 那么你需要一个 capturing group 所以

    'blah blah ???5/28/24 15:55??? blah blah blah' -match '\?{3}(.*\s.*)\?{3}'
    $Matches[1] # => 5/28/24 15:55
    

    看见 https://regex101.com/r/0DgImA/1 有关regex的详细信息。

    另一个可能适用于您的用例的选项是使用 lookbehind assertion :

    'blah blah ???5/28/24 15:55??? blah blah blah' -match '(?<=\?{3})[^?]+'
    $Matches[0] # => 5/28/24 15:55
    

    看见 https://regex101.com/r/n7g4qP/1 有关regex的详细信息。

    推荐文章