编辑 2020-05-23:我已将代码移至 GitHub,在这里,我进行了更新以涵盖一些边缘情况:https ://github.com/franklesniak/PowerShell_Resources/blob/master/Split-StringOnLiteralString .ps1
-split 运算符需要 RegEx,但可以很好地做到这一点。但是,-split 运算符仅在 Windows PowerShell v3+ 上可用,因此它不符合问题中的要求。
[regex] 对象有一个 Split() 方法也可以处理这个问题,但它希望 RegEx 作为“拆分器”。为了解决这个问题,我们可以使用第二个 [regex] 对象并调用 Escape() 方法将我们的文字字符串“splitter”转换为转义的 RegEx。
将所有这些封装成一个易于使用的函数,该函数可回溯到 PowerShell v1,也适用于 PowerShell Core v6。
function Split-StringOnLiteralString
{
trap
{
Write-Error "An error occurred using the Split-StringOnLiteralString function. This was most likely caused by the arguments supplied not being strings"
}
if ($args.Length -ne 2) `
{
Write-Error "Split-StringOnLiteralString was called without supplying two arguments. The first argument should be the string to be split, and the second should be the string or character on which to split the string."
} `
else `
{
if (($args[0]).GetType().Name -ne "String") `
{
Write-Warning "The first argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strToSplit = [string]$args[0]
} `
else `
{
$strToSplit = $args[0]
}
if ((($args[1]).GetType().Name -ne "String") -and (($args[1]).GetType().Name -ne "Char")) `
{
Write-Warning "The second argument supplied to Split-StringOnLiteralString was not a string. It will be attempted to be converted to a string. To avoid this warning, cast arguments to a string before calling Split-StringOnLiteralString."
$strSplitter = [string]$args[1]
} `
elseif (($args[1]).GetType().Name -eq "Char") `
{
$strSplitter = [string]$args[1]
} `
else `
{
$strSplitter = $args[1]
}
$strSplitterInRegEx = [regex]::Escape($strSplitter)
[regex]::Split($strToSplit, $strSplitterInRegEx)
}
}
现在,使用前面的示例:
PS C:\Users\username> Split-StringOnLiteralString "One two three keyword four five" "keyword"
One two three
four five
沃拉!