How to split string by string in Powershell

后端 未结 5 1182
既然无缘
既然无缘 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条回答
  •  旧时难觅i
    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.

提交回复
热议问题