Strange result from String.Split()

前端 未结 4 723
半阙折子戏
半阙折子戏 2021-01-15 02:59

Why does the following result in an array with 7 elements with 5 blank? I\'d expect only 2 elements. Where are the 5 blank elements coming from?

$a = \'OU=RA         


        
4条回答
  •  被撕碎了的回忆
    2021-01-15 03:29

    String.Split() is character oriented. It splits on O, U, = as three separate places.

    Think of it as intending to be used for 1,2,3,4,5. If you had ,2,3,4, it would imply there were empty spaces at the start and end. If you had 1,2,,,5 it would imply two empty spaces in the middle.

    You can see with something like:

    PS C:\> $a = 'OU=RAH,OU=RAC'
    PS C:\> $a.Split('RAH')
    OU=
    
    
    ,OU=
    
    C
    

    The spaces are R_A_H and R_A. Split on the end of a string, it introduces blanks at the start/end.

    PowerShell's -split operator is string oriented.

    PS D:\t> $a = 'OU=RAH,OU=RAC'
    
    PS D:\t> $a -split 'OU='
    
    RAH,
    RAC
    

    You might do better to split on the comma, then replace out OU=, or vice versa, e.g.

    PS D:\t> $a = 'OU=RAH,OU=RAC'
    
    PS D:\t> $a.Replace('OU=','').Split(',')
    RAH
    RAC
    

提交回复
热议问题