gpt4 book ai didi

regex - -匹配成功但不更新 $matches

转载 作者:行者123 更新时间:2023-12-02 01:09:52 25 4
gpt4 key购买 nike

我编写了一个脚本来调用外部命令并使用正则表达式捕获其输出的一部分。这是一个示例(非真实世界)脚本,用于演示我是如何执行此操作的:

$output = clip
if ($output -imatch 'usage')
{
Write-Output $matches[0]
}

如果我在命令提示符下运行 clip,它的输出如下所示:

INFO: Type "CLIP /?" for usage.

在上面的代码中,匹配成功,但是没有设置$matches。如果我使用如下不同的方法设置 $output,问题就会消失:

$output = 'INFO: Type "CLIP /?" for usage.'

为什么在调用命令时未设置 $matches?我该如何解决这个问题?

最佳答案

当你不带参数运行clip.exe时,结果是:

PS > clip

Infos : Entrez "CLIP /?" pour afficher la syntaxe.

产生了两条线:

  1. 回车/换行(空)
  2. 第二行文字

因此,当您编写 $output = clip 时,您是在将一个数组分配给 $output$output[0] 是空行,$output[1] 是文本行。 Out-String cmdlet 删除了不必要的 CR/LF。

你可以尝试这样的事情:

clip | where {$_ -imatch 'syntaxe'} | % {$matches}

已编辑

据我了解,未填充$matches 的原因是-imatch 的输入是一个数组。正如您在 about_comparison_Operators 中所读到的那样:

"When the input is scalar, it [-match operator] populates the $Matches automatic variable.

关于regex - -匹配成功但不更新 $matches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18564931/

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