5

在 PowerShell 中对字符串使用 .Split() 运算符并尝试使用多个字符的字符串进行拆分时,PowerShell 会表现出奇怪的行为 - 它使用字符串中的任何字符进行拆分。

例如:

PS C:\Users\username> "One two three keyword four five".Split("keyword")
On
 t

 th









 f
u
 fiv

我不了解你,但我期待结果是一个数组,如:

@("One two three "," four five")

如何拆分字符串,将“拆分器”视为文字字符串?对于那些来自 VBScript 的人来说,这就是内置的 Split() 函数在 VBScript 中的行为方式。

其他几点注意事项:

  • 我做了一些搜索,发现了一些使用 RegEx 的建议解决方案;如果可以避免,我宁愿不使用它。
  • 我想要一个适用于所有版本的 PowerShell 的解决方案。
4

2 回答 2

4

无需创建函数。

您可以通过split两种不同的方式使用该功能。如果您使用:

"One two three keyword four five".Split("keyword")

括号内的每个字符都用作分隔符。但是,如果您改为使用:

"One two three keyword four five" -Split ("keyword")

字符串“keyword”用作分隔符。

于 2018-11-19T07:24:10.850 回答
3

编辑 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

沃拉!

于 2018-11-19T05:10:08.800 回答