regex - [Regex]::Match() 在 If 内部和外部的行为不同(也使用 [Regex]::Match() )
问题描述
给定一个 uninstallString 的"C:\ProgramData\Package Cache\{56e11d69-7cc9-40a5-a4f9-8f6190c4d84d}\VC_redist.x86.exe" /uninstall
I 可以成功提取带引号的文本([Regex]::Match($uninstallString, '^\".*\"').Value)
。但是,如果我测试该字符串是否具有所需的 /uninstall 位,则尝试提取带引号的位,如下所示...
if ([Regex]::Match($uninstallString, '^\".*\" +/uninstall').Succes) {
([Regex]::Match($uninstallString, '^\".*\"').Value)
}
它的值不是完整的字符串,而是仅返回 "C:\ProgramData\Package
. 现在,我的理解是。是除了换行符之外的所有内容,因此空格应该没问题。但是,如果我用字符串中的下划线替换空格,它会按预期工作,所以它肯定是导致问题的空格。另外,我很困惑为什么它在 If 之外有效,但在内部无效。我的印象是,使用 [Regex]::Match() 会在每次使用时创建单独的对象,它们不会相互交互,但在这里似乎它们是。
解决方案
由于您想查看是否找到了引用的字符串(路径)并且它是否包含开关“/卸载”,我会做这样的事情:
$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
}
推荐阅读
- android - Mapbox Android 中的可绘制资源
- css - 过渡后执行css
- excel - Excel 查询连接表
- json - WSO2 EI 从注册表中读取 json
- python - 使用 Python Mido 库选择 GM MIDI Level 2 乐器
- python - Elasticsearch与python如何在SQL请求之类的字符串中查找子字符串?
- javascript - Javascript基于递增键合并对象数组
- swift - 应用程序因错误而崩溃:无法推断通用参数“T”
- css - 为什么我们可以在 box-shadow 规则中首先获得颜色值?
- sql - 在 Azure SQL Server 中将无拉丁字符转换为拉丁字符