求助:通配符匹配函数输出出现意外索引数字及匹配异常
通配符匹配(Wildcard Matching)
我写了一个wildCard-Replace函数,用来枚举环境变量并找出通配符返回时的最小公分母。但输出里莫名出现了0-8这些数字,推测是索引位置,但我没指定输出它们,这是ArrayList的问题吗?
另外,函数是反向处理字符的,现在会匹配带?的环境变量并解析,我试了各种错误处理都没能解决这个问题。
输出示例
0 1 2 3 4 5 6 7 8 ${env:userdomai?} ${env:userdoma??} ${env:userdom???} ${env:userdo????} ${env:userd?????} ${env:user??????} ${env:use???????} ${env:us????????} ${env:u?????????}
函数代码
function wildCard-Replace { param ( [string]$string ) $modifiedString = $string $options = New-Object System.Collections.ArrayList $yup = New-Object System.Collections.ArrayList # Iterate through each character in the string in reverse order for ($i = $string.Length - 1; $i -ge 0; $i--) { # Replace the character with a question mark $modifiedString = $modifiedString.Substring(0, $i) + "?" + $modifiedString.Substring($i + 1) $ModStringValue = (get-item "env:$modifiedString").value $constant = ('${'+"env:$string}").Value $validated = ('${'+"env:$modifiedString}") if (($modifiedString -match "[^?]") -and ($ModStringValue -like "*$constant*")){ $yup.Add($validated) #| Out-Null } } return $yup }
问题解决
1. 输出中0-8数字的来源
这些数字是ArrayList.Add()方法的返回值——它会返回新元素在列表中的索引位置。PowerShell会自动输出所有未被抑制的命令返回值,所以这些索引被一起输出了。
解决方法很简单,只需要抑制Add()的返回值:
- 方法一:在
Add()后加| Out-Null:$yup.Add($validated) | Out-Null - 方法二:用
[void]强制忽略返回值:[void]$yup.Add($validated) - 方法三:改用PowerShell原生数组(无需处理返回值):
# 初始化时改成原生数组 $yup = @() # 添加元素时用+= $yup += $validated
2. 意外匹配带?的环境变量问题
原代码中Get-Item "env:$modifiedString"会把?当作PowerShell通配符(匹配单个任意字符),所以会自动匹配符合模式的环境变量。如果要精确匹配带?的环境变量名,需要使用-LiteralPath参数,让PowerShell把?当作字面量处理:
$ModStringValue = (Get-Item -LiteralPath "env:$modifiedString").Value
另外,原代码中$constant的赋值逻辑错误:('${'+"env:$string}").Value是对字符串调用.Value属性,这完全无效,应该直接获取原环境变量的实际值:
$constant = (Get-Item -LiteralPath "env:$string").Value
如果你的需求是验证通配符替换后的环境变量值是否包含原环境变量值,当前的$ModStringValue -like "*$constant*"逻辑是对的;如果逻辑反了,可以调整为$constant -like "*$ModStringValue*",根据实际需求修改即可。
内容的提问来源于stack exchange,提问作者I am Jakoby
相关产品推荐
相关产品推荐

