ZIP code regex C#

ZIP code

ZIP code (US postal code) regular expression can be used to verify if a given string contains a valid ZIP code or extract ZIP code from a string. Supports both 5-digit and 9-digit (ZIP+4) formats.

ZIP code regex

A regular expression to test a string against ZIP code format:

new Regex("^[0-9]{5}(?:-[0-9]{4})?$")

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Example code in C#:

using System.Text.RegularExpressions;
using System.Linq;
using System;
                    
public class Program
{
    public static void Main()
    {
        // Validate ZIP code
        Regex validateZipRegex = new Regex("^[0-9]{5}(?:-[0-9]{4})?$");
        Console.WriteLine(validateZipRegex.IsMatch("word"));  // prints True
        
        // Extract ZIP code from a string
        Regex extractZipRegex = new Regex("[0-9]{5}(?:-[0-9]{4})?");
        string [] extracted = extractZipRegex.Matches("My zip code is 80001")
            .Cast()
            .Select(m => m.Value) 
            .ToArray(); 
        Console.WriteLine(String.Join(",", extracted)); // prints 80001
    }
}

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Test it!
This is some text inside of a div block.

True

False

Enter a text in the input above to see the result

Notes on ZIP code validation and extraction

This ZIP code regex has several limitations:

  • It only works for US ZIP codes. If you need to support other countries, you might need to have a separate regular expression for each one of them and execute it based on the country provided.
  • It can not guarantee that ZIP code actually exists. For instance, 99999 is a correct format, but this ZIP code does not exist.
  • The extraction method can generate false-positive extraction if a string contains multiple numbers.