首页 > 解决方案 > [Regex]::Match() 在 If 内部和外部的行为不同(也使用 [Regex]::Match() )

问题描述

给定一个 uninstallString 的"C:\ProgramData\Package Cache\{56e11d69-7cc9-40a5-a4f9-8f6190c4d84d}\VC_redist.x86.exe" /uninstallI 可以成功提取带引号的文本([Regex]::Match($uninstallString, '^\".*\"').Value)。但是,如果我测试该字符串是否具有所需的 /uninstall 位,则尝试提取带引号的位,如下所示...

if ([Regex]::Match($uninstallString, '^\".*\" +/uninstall').Succes) {
    ([Regex]::Match($uninstallString, '^\".*\"').Value)
}

它的值不是完整的字符串,而是仅返回 "C:\ProgramData\Package. 现在,我的理解是。是除了换行符之外的所有内容,因此空格应该没问题。但是,如果我用字符串中的下划线替换空格,它会按预期工作,所以它肯定是导致问题的空格。另外,我很困惑为什么它在 If 之外有效,但在内部无效。我的印象是,使用 [Regex]::Match() 会在每次使用时创建单独的对象,它们不会相互交互,但在这里似乎它们是。

标签: regexpowershell

解决方案


由于您想查看是否找到了引用的字符串(路径)并且它是否包含开关“/卸载”,我会做这样的事情:

$uninstallString = '"C:\ProgramData\Package Cache\{56e11d69-7cc9-40a5-a4f9-8f6190c4d84d}\VC_redist.x86.exe"'

if ($uninstallString -match '^(?<path>".*")(?:\s+(?<switch>/uninstall))?') {
    $uninstallPath   = $matches['path']    # at least the path (quoted string) is found
    $uninstallSwitch = $matches['switch']  # if '/uninstall' switch is not present, this will result in $null
}

推荐阅读