How to split string by string in Powershell

后端 未结 5 1158
既然无缘
既然无缘 2020-12-03 16:49

I\'m trying to spit the string with a delimiter, which is a string:

$string = \"5637144576, messag<>est<<>>5637145326, 1<<>>563         


        
相关标签:
5条回答
  • 2020-12-03 17:29

    The following should be what you need:

     $string -Split $separator
    

    This produces:

    5637144576, messag<>est
    5637145326, 1
    5637145328, 0
    
    0 讨论(0)
  • 2020-12-03 17:29

    EDIT 2020-05-23: I've moved my code to GitHub, here, where I've made updates to cover a few edge cases: https://github.com/franklesniak/PowerShell_Resources/blob/master/Split-StringOnLiteralString.ps1


    You can use the -split operator, but it expects RegEx. Furthermore, the -split operator is only available on Windows PowerShell v3+, so we need a different method if you want something that is universally compatible with all versions of PowerShell.

    A [regex] object has a Split() method that can handle this as well, but again, it expects RegEx as the "splitter". To get around this, we can use a second [regex] object and call the Escape() method to convert our literal string "splitter" into escaped RegEx.

    Wrapping all this up into an easy to use function that works back to PowerShell v1 and also works on 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)
        }
    }
    

    Now, using the earlier example:

    PS C:\Users\username> Split-StringOnLiteralString "5637144576, messag<>est<<>>5637145326, 1<<>>5637145328, 0" "<<>>"
    5637144576, messag<>est
    5637145326, 1
    5637145328, 0
    

    Volla!

    0 讨论(0)
  • 2020-12-03 17:34

    Sometimes PowerShell looks exactly like C# and at others, well you know...

    It could also be used thus:

    # 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")
    }
    
    0 讨论(0)
  • 2020-12-03 17:36

    The -split operator uses the string to split, instead of a chararray like Split():

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

    If you want to use the Split() method with a string, you need the $seperator to be a stringarray with one element, and also specify a stringsplitoptions value. You can see this by checking its definition:

    $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
    

    EDIT: As @RomanKuzmin pointed out, -split splits using regex-patterns by default. So be aware to escape special characters (ex. . which in regex is "any character"). You could also force simplematch to disable regex-matching like:

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

    Read more about -split here.

    0 讨论(0)
  • 2020-12-03 17:42

    Instaed of using Split method, you can use split operator. So your code will be like this:

    $string -split '<<>>'
    
    0 讨论(0)
提交回复
热议问题