如何在Powershell中逐字符串拆分

时间:2013-05-08 07:42:37

标签: powershell

我正在尝试使用分隔符吐出字符串,这是一个字符串:

$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string.Split($separator)

由于分裂,我得到:

5637144576, messag

est



5637145326, 1



5637145328, 0

而不是

5637144576, messag<>est
5637145326, 1
5637145328, 0

当我尝试使用接受string []的重载拆分时:

$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = @("<<>>")
$string.Split($separator)

但我得到了下一个错误:

Cannot convert argument "0", with value: "System.Object[]", for "Split" to type "System.Char[]": "Cannot convert value "<<>>" to type "System.Char". Error: "String must be exactly one character long.""

有人知道如何按字符串拆分字符串吗?

5 个答案:

答案 0 :(得分:25)

-split运算符使用字符串进行拆分,而不是Split()之类的字符:

$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = "<<>>"
$string -split $separator

5637144576, messag<>est
5637145326, 1
5637145328, 0

如果要将Split()方法与字符串一起使用,则需要$seperator为包含一个元素的字符串,并指定stringsplitoptions值。您可以通过检查其定义来看到这一点:

$string.Split

OverloadDefinitions                                                                                
-------------------                                                                                
string[] Split(Params char[] separator)                                                            
string[] Split(char[] separator, int count)                                                        
string[] Split(char[] separator, System.StringSplitOptions options)                                
string[] Split(char[] separator, int count, System.StringSplitOptions options)                     

#This one
string[] Split(string[] separator, System.StringSplitOptions options)      
string[] Split(string[] separator, int count, System.StringSplitOptions options)


$string = "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0"
$separator = [string[]]@("<<>>")
$string.Split($separator, [System.StringSplitOptions]::RemoveEmptyEntries)

5637144576, messag<>est
5637145326, 1
5637145328, 0
编辑:正如@RomanKuzmin指出的那样,-split默认使用正则表达式模式进行拆分。所以要注意逃避特殊字符(例如.,其中正则表达式是“任何字符”)。您还可以强制simplematch禁用正则表达式匹配,如:

$separator = "<<>>"
$string -split $separator, 0, "simplematch"

详细了解-split here

答案 1 :(得分:1)

您可以使用Split运算符,而不是使用split方法。所以你的代码将是这样的:

$string -split '<<>>'

答案 2 :(得分:1)

有时PowerShell看起来和C#完全一样,而其他人,你知道......

也可以这样使用:

# A dummy text file
$text = @'
abc=3135066977,8701416400

def=8763026853,6433607660

xyz=3135066977,9878763344
'@ -split [Environment]::NewLine,[StringSplitOptions]"RemoveEmptyEntries"

"`nBefore `n------`n"

$text

"`nAfter `n-----`n"

# Do whatever with this
foreach ($line in $text)
{
    $line.Replace("3135066977","6660985845")
}

答案 3 :(得分:0)

以下内容应该是您所需要的:

 $string -Split $separator

这会产生:

5637144576, messag<>est
5637145326, 1
5637145328, 0

答案 4 :(得分:0)

您可以使用-split运算符,但需要RegEx。此外,-split运算符仅在Windows PowerShell v3 +上可用,因此如果您需要与所有版本的PowerShell通用兼容的东西,我们需要使用其他方法。

[regex]对象具有一个Split()方法也可以处理此问题,但是同样,它希望RegEx作为“分割器”。为了解决这个问题,我们可以使用第二个[regex]对象并调用Escape()方法,将文字字符串“ splitter”转换为转义的RegEx。

将所有这些包装到一个易于使用的功能中,该功能可以回溯到PowerShell v1,也可以在PowerShell Core 6.x上使用。

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 "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0" "<<>>"
5637144576, messag<>est
5637145326, 1
5637145328, 0

Volla!