Powershell split() vs -split - what's the difference?

后端 未结 3 736
萌比男神i
萌比男神i 2020-12-07 05:18

After struggling with this for half an hour, I\'ve experienced this difference when splitting a string with spaces, depending on which syntax you use.

Simple string:

3条回答
  •  Happy的楠姐
    2020-12-07 05:37

    1. .Net object does not take regex but interprets it as a literal string.

      $line = "1: 2: 3: 4: 5: "
      $ln = $line.split("\s")
      $ln
      

    Output:

    1: 2: 3: 4: 5: 
    

    Hence, in your example, the "+" is ignored as it it not found in $ln but ":\s" is used for splitting:

    $ln = $line.split(":\s+")
    $ln
    
    Output: 
    
    1
     2
     3
     4
     5
    

    which is same as

    $ln = $line.split(":")
    $ln
    

    2.while powershell -split operator interprets "\s" as a valid regex i.e., space. Since, it can find both : and \s in the string, the combination of ":\s" is used for splitting. eg:

    $line = "1:2:3: 4: 5: "
    $ln = $line -split ":"
    $ln
    

    output:

    1
    2
    3
     4
     5
    

提交回复
热议问题