Fra*_*iak 5 string powershell split
在 PowerShell 中对字符串使用 .Split() 运算符并尝试使用一个以上字符的字符串进行拆分时,PowerShell 会表现出奇怪的行为 - 它使用字符串中的任何字符进行拆分。
例如:
PS C:\Users\username> "One two three keyword four five".Split("keyword")
On
t
th
f
u
fiv
Run Code Online (Sandbox Code Playgroud)
我不了解你,但我希望结果是一个像这样的数组:
@("One two three "," four five")
Run Code Online (Sandbox Code Playgroud)
如何拆分字符串,将“拆分器”视为文字字符串?对于那些来自 VBScript 的人来说,这就是内置的 Split() 函数在 VBScript 中的表现。
其他一些注意事项:
小智 7
无需创建函数。
您可以split通过两种不同的方式使用该函数。如果您使用:
"One two three keyword four five".Split("keyword")
Run Code Online (Sandbox Code Playgroud)
括号内的每个字符都用作分隔符。但如果你改为使用:
"One two three keyword four five" -Split ("keyword")
Run Code Online (Sandbox Code Playgroud)
字符串“keyword”用作分隔符。
编辑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)
}
}
Run Code Online (Sandbox Code Playgroud)
现在,使用前面的示例:
PS C:\Users\username> Split-StringOnLiteralString "One two three keyword four five" "keyword"
One two three
four five
Run Code Online (Sandbox Code Playgroud)
沃拉!