Strange result from String.Split()

前端 未结 4 722
半阙折子戏
半阙折子戏 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:31

    It splits the string for each character in the separator. So its splitting it on 'O', 'U' & '='.

    As @mklement0 has commented, my earlier answer would not work in all cases. So here is an alternate way to get the expected items.

    $a.Split(',') |% { $_.Split('=') |? { $_ -ne 'OU' } }
    

    This code will split the string, first on , then each item will be split on = and ignore the items that are OU, eventually returning the expected values:

    RAH
    RAC
    

    This will work even in case of:

    $a = 'OU=FOO,OU=RAH,OU=RAC'
    

    generating 3 items FOO, RAH & RAC

    To get only 2 string as expected you could use following line: $a.Split('OU=', [System.StringSplitOptions]::RemoveEmptyEntries) Which will give output as: RAH, RAC And if you use (note the comma in the separator) $a.Split(',OU=', [System.StringSplitOptions]::RemoveEmptyEntries) you will get RAH RAC

    This is probably what you want. :)

提交回复
热议问题