我突然似乎无法分割字符串,而我之前已经成功地做到了这一点。该字符串是 Get-ChildItem 的排除列表,我希望以更易读的格式显示该列表,以便用户可以轻松验证它们是否正确。
我使用的是 PowerShell 7.3.4。代码:
# Regular expression of files/folders to exclude from the search
$exclusions = "\.bak| - Copy|\.db|\.ini|\.log|\.temp|template|test|\.tmp|New-Folder|prototype|_vti"
$substrings = $exclusions -split "|"
$substrings
$count = $substrings.count
Write-Host "Number of exclusions: $count"
foreach ($string in $substrings) {
Write-Host "► $_"
}
唯一的输出正确地显示“排除数:12”,但从未显示它们。
反斜杠告诉正则表达式解析器按字面意思处理句点。反斜杠会干扰 -Split 调用吗?
最佳答案
两个问题:
- 您需要在正则表达式模式中转义
|
,例如。... -split '\|'
- 您使用
$string
作为迭代器变量,但在循环中引用$_
解决这两个问题,它就会按预期工作:
$exclusions = "\.bak| - Copy|\.db|\.ini|\.log|\.temp|template|test|\.tmp|New-Folder|prototype|_vti"
$substrings = $exclusions -split "\|"
$count = $substrings.count
Write-Host "Number of exclusions: $count"
foreach ($string in $substrings) {
Write-Host "► $string"
}
输出:
Number of exclusions: 12
► \.bak
► - Copy
► \.db
► \.ini
► \.log
► \.temp
► template
► test
► \.tmp
► New-Folder
► prototype
► _vti
关于PowerShell - 无法拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76347617/