title: Get first part of UK postcode only
body: <p>I'm trying to get the first part of a UK postcode from a string that may have only the first part of the postcode or the full postcode in it. I'm struggling to make it work. I've got it working if the full postcode is entered by using a look-ahead, but I can't seem to make the look-ahead optional, so if only the first part of the postcode is entered it is matched.</p>
  
  <p>My regex so far is <code>([A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW])(?=( ?[0-9][ABD-HJLNP-UW-Z]{2})))</code></p>
  
  <p>I've got several postcodes that must match and these are the results using the above regex:</p>
  
  <pre><code>A10EA     - Should match and does
  A1        - Should match but doesn't
  A10 0EA   - Should match and does
  A10       - Should match but doesn't
  BH18 1AE  - Should match and does
  BH18AE    - Should match and does
  EC1M 6HJ  - Should match and does
  EC1M      - Should match but doesn't
  Z10 2EV   - Shouldn't match and doesn't
  QE3 6DA   - Shouldn't match but matches E3 6DA
  </code></pre>
  
  <p>Can someone please help me solve this issue?</p>
  
  <p>The RegEx I've been working from is the official one from the post office:</p>
  
  <pre><code>/^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$/i
  </code></pre>
  
  <p>Before anyone flags this as a duplicate of <a href="https://stackoverflow.com/questions/16359481/php-find-first-part-of-uk-postcode-when-full-or-part-can-be-entered">PHP Find first part of UK postcode when full or part can be entered</a>, it's not. The answer for that question doesn't work, see my comment to the answer.</p>