<p>I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance:</p>

<p><strong>Matches</strong></p>

<ul>
<li>CW3 9SS</li>
<li>SE5 0EG</li>
<li>SE50EG</li>
<li>se5 0eg</li>
<li>WC2H 7LT</li>
</ul>

<p><strong>No Match</strong></p>

<ul>
<li>aWC2H 7LT</li>
<li>WC2H 7LTa</li>
<li>WC2H</li>
</ul>

<p>How do I solve this problem?</p>

```
```
^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$
```
```
Regular expression to match valid UK
  postcodes. In the UK postal system not
  all letters are used in all positions
  (the same with vehicle registration
  plates) and there are various rules to
  govern this. This regex takes into
  account those rules. Details of the
  rules: First half of postcode Valid
  formats [A-Z][A-Z][0-9][A-Z]
  [A-Z][A-Z][0-9][0-9] [A-Z][0-9][0-9]
  [A-Z][A-Z][0-9] [A-Z][A-Z][A-Z]
  [A-Z][0-9][A-Z] [A-Z][0-9] Exceptions
  Position - First. Contraint - QVX not
  used Position - Second. Contraint -
  IJZ not used except in GIR 0AA
  Position - Third. Constraint -
  AEHMNPRTVXY only used Position -
  Forth. Contraint - ABEHMNPRVWXY Second
  half of postcode Valid formats
  [0-9][A-Z][A-Z] Exceptions Position -
  Second and Third. Contraint - CIKMOV
  not used
http://regexlib.com/REDetails.aspx?regexp_id=260