Home > Enterprise >  Correct regex pattern for targeting specific sectors within UK Postcode
Correct regex pattern for targeting specific sectors within UK Postcode

Time:01-05

What is the correct way to only target LA7, LA8, LA9, LA11, LA12, LA21, LA22, LA23, CA10, CA11 and CA12.

I have done the pattern seperately but I imagine this is not the most efficient or correct way to do it.

/^(LA[7-9A-Z]? ?\d[0-9A-Z]{2}|LA[11-12A-Z]? ?\d[0-9A-Z]{2}|LA[21-23A-Z]? ?\d[0-9A-Z]{2}|CA[10-12A-Z]? ?\d[0-9A-Z]{2})$/

CodePudding user response:

If the point is to only match these specific codes as standalone strings, you can use

^(?:LA(?:2[123]|1[12]|[789])|CA1[012])$

See this regex demo.

To match them in a longer text, you can use a regex variation with word boundaries:

\b(?:LA(?:2[123]|1[12]|[789])|CA1[012])\b

Details:

  • ^ - start of a string
  • (?:LA(?:2[123]|1[12]|[789])|CA1[012]) - either of the two alternatives:
    • LA(?:2[123]|1[12]|[789]) - LA and then either 2 followed with 1, 2 or 3, or 1 followed with 1 or 2, or 7, 8 or 9
    • | - or
    • CA1[012] - CA1 and then 0, or 1, or 2
  • $ - end of string.
  • Related