title: PowerShell use regular expression to split a string
body: <p>This is my code:</p>
  
  <pre><code>[regex]::split("1,2   3", '(,|\s)+')
  </code></pre>
  
  <p>What I want is an array with three elements <code>1, 2, 3</code>, however, what I got it is an array with five elements.</p>
  
  <pre><code>PS C:\Users\a&gt; [regex]::split("1,2   3", '(,|\s)+').Length
  5
  PS C:\Users\a&gt;
  </code></pre>
  
  <p>How to get what I want?</p>
  
  <h1>Update</h1>
  
  <p>Add the actual <code>split</code> result instead of the <code>length</code>.</p>
  
  <pre><code>PS E:\&gt; [regex]::split("1,2   3", '(,|\s)+')
  1
  ,
  2
  
  3
  PS E:\&gt; [regex]::split("1,2   3", '(,|\s)+').length
  5
  PS E:\&gt; [regex]::split("1,2   3", '[,\s]+')
  1
  2
  3
  PS E:\&gt; [regex]::split("1,2   3", '[,\s]+').length
  3
  PS E:\&gt;
  </code></pre>
  
  <h1>Update</h1>
  
  <p>Thanks @Matt's answer and it points me to the right direction. From <code>help about_split</code> the doc states that:</p>
  
  <blockquote>
    <p>By default, the delimiter is omitted from the results. To preserve all
    or part of the delimiter, enclose in parentheses the part that you
    want to preserve.</p>
  </blockquote>
  
  <p>Below are some of my testing.</p>
  
  <pre><code>PS E:\tutorial&gt;     "Lastname/:/FirstName/:/Address" -split "/(:)/"
  Lastname
  :
  FirstName
  :
  Address
  PS E:\tutorial&gt;     "Lastname/:/FirstName/:/Address" -split "/:/"
  Lastname
  FirstName
  Address
  PS E:\tutorial&gt;     "Lastname/:/FirstName/:/Address" -split "(/:/)"
  Lastname
  /:/
  FirstName
  /:/
  Address
  PS E:\tutorial&gt;     "Lastname/:/FirstName/:/Address" -split "/:(/)"
  Lastname
  /
  FirstName
  /
  Address
  PS E:\tutorial&gt;     "Lastname/:/FirstName/:/Address" -split "(/):(/)"
  Lastname
  /
  /
  FirstName
  /
  /
  Address
  PS E:\tutorial&gt;     "Lastname/:/FirstName/:/Address" -split "(/)(:)(/)"
  Lastname
  /
  :
  /
  FirstName
  /
  :
  /
  Address
  PS E:\tutorial&gt; [regex]::split("Lastname/:/FirstName/:/Address", '/(:)/')
  Lastname
  :
  FirstName
  :
  Address
  PS E:\tutorial&gt; [regex]::split("Lastname/:/FirstName/:/Address", '/:/')
  Lastname
  FirstName
  Address
  PS E:\tutorial&gt; [regex]::split("Lastname/:/FirstName/:/Address", '/:(/)')
  Lastname
  /
  FirstName
  /
  Address
  PS E:\tutorial&gt; [regex]::split("Lastname/:/FirstName/:/Address", '(/):(/)')
  Lastname
  /
  /
  FirstName
  /
  /
  Address
  PS E:\tutorial&gt; [regex]::split("Lastname/:/FirstName/:/Address", '(/)(:)(/)')
  Lastname
  /
  :
  /
  FirstName
  /
  :
  /
  Address
  PS E:\tutorial&gt;
  </code></pre>