【问题标题】:Powershell Regex groupsPowershell 正则表达式组
【发布时间】:2021-09-27 23:42:12
【问题描述】:

我正在尝试使用 Regex 从字符串中获取已安装应用程序的路径,但无法理解我看到的结果。

我的字符串包含我想要查找“C:\GPONew\XPP\xz\bin”的路径,并且我想要捕获“C:\GPONew\XPP”并测试我正在测试的脚本对于 "\xzX\bin" 给出错误结果:

$path = "C:\GPONew\XPP\Perl\site\bin;C:\GPONew\XPP\Perl\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\GPONew\XPP\xz\bin"
$path -match "([A-Z]{1}:\\[^;]*\\XPP)\\xzX\\bin"
$Matches

这会为 $Matches 输出 False,但确实给了我无法理解的捕获组,因为它不应该与“xz”中的额外 X 匹配。

False

Name                           Value                                                                                                                               
----                           -----                                                                                                                               
1                              C:\GPONew\XPP                                                                                                                       
0                              C:\GPONew\XPP\xz\bin

最重要的是,文档Groups, Captures, and Substitutions 继续说我可以使用任何哈希表方法访问 $Matches 以访问存储的值。

$Matches.0 或 $Matches.1 但这给了我错误:

Unexpected token '.0' in expression or statement.
+ $Matches.0 <<<< 
    + CategoryInfo          : ParserError: (.0:String) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

而我必须改用 $Matches[0]

我使用 Powershell V 2.0 是否有影响?

编辑:

在 Wiktor Stribiżew 发表评论后,我关闭了我的 ISE 并再次打开它,不再获得任何与 False 匹配的匹配,但是一旦我将匹配更改为 True,然后将其更改回为 false ,即使我有以下情况,我也会继续获得匹配项:

clear
$path = "C:\GPONew\XPP\Perl\site\bin;C:\GPONew\XPP\Perl\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\GPONew\XPP\xz\bin"
$path -match "([A-Z]{1}:\\[^;]*\\XPP)\\xzABC\\bin"
clear
$Matches

输出

False

Name                           Value                                                                                                                               
----                           -----                                                                                                                               
1                              C:\GPONew\XPP                                                                                                                       
0                              C:\GPONew\XPP\xz\bin  

【问题讨论】:

  • 我得到一个空的 $Matches 输出 - 你确定你在干净的控制台中运行你的代码吗?
  • 奇怪,我在控制台中输入 clear 然后在第一行添加 clear 并且仍然得到匹配。关闭 ISE 并再次打开,现在我没有。

标签: regex powershell


【解决方案1】:

您误会了clear 的作用。该 cmdlet 只清除屏幕,而不是变量。如果您想清除自动变量$Matches 的内容,您将需要改用Clear-Variable Matches。您看到的是预期行为。

【讨论】:

  • 太棒了,谢谢。我确实弄错了 clear 做了什么!
  • 如果此答案解决了问题,请使用左侧的复选标记将其标记为已接受,以帮助未来遇到类似问题的用户更快地找到功能性答案。
猜你喜欢
  • 2012-08-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 2021-11-25
  • 2018-07-05
  • 2017-10-10
  • 2012-06-20
相关资源
最近更新 更多