【发布时间】: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