gpt4 book ai didi

regex - Powershell 正则表达式混淆

转载 作者:行者123 更新时间:2023-12-01 12:15:41 24 4
gpt4 key购买 nike

目标字符串:

8AM - 10AM (local time)
12PM - 1PM (local time)

我可以从 https://regexr.com/ 中提取时间用这个表达式:

\d{1,2}(AM|PM)

但是,我无法在 powershell 中这样做:

cls
$var = "8AM - 10AM (local time)
12PM - 1PM (local time)"
if ($var -match "\d{1,2}(AM|PM)")
{
$matches
}

PS输出:

Name    Value                                                                                                                                                                                                            
---- -----
1 AM
0 8AM

但是,当我在PS中使用下面的脚本时:

cls
$var = "8AM - 10AM (local time)"
[regex]::Matches($var,"\d{1,2}(AM|PM)").Value

它给出了正确的输出:

8AM
10AM

关于为什么会发生这种情况有什么想法吗?

最佳答案

  • -match运算符只会查找最多 1 个匹配项。

    • [regex]::Matches()如果您需要多个匹配项,确实是正确的选择。
    • 或者,使用 Select-String cmdlet,但是会慢很多:
      ('8AM - 10AM (local time)' | Select-String -AllMatches '\d{1,2}(AM|PM)').Matches.Value
  • 因此,-match , 自动 $Matches results 变量仅包含有关那 1 个匹配项的信息,可能包括 capture-group 匹配项。

    • (AM|PM)你的正则表达式的一部分是一个捕获组,所以对于第一个整体匹配 - 8AM - 捕获组的结果是 AM .
    • $Matches[hashtable]其条目为 0键包含整体匹配;条目 <n>包含第 n 个(未命名的)捕获组结果。
    • [hashtable] 的条目枚举以来没有保证顺序发生,1条目恰好列在 0 之前在这种情况下进入。

关于regex - Powershell 正则表达式混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48455598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com