Advertisement

Pattern library / Validation

Country Code Regex (ISO 3166)

Two letters, uppercase: that is the alpha-2 shape every API expects (ID, US, GB). Regex can prove the shape — two letters, no more — but not that the code is one of the ~249 real countries; that step is a set lookup, and the notes show the exact pattern for each ISO variant.

The pattern
^[A-Z]{2}$
Load this pattern into the tester →

How the pattern works

Test it: match & no-match examples

Every row is loaded straight into the tester — click Try to see the match live:

InputResultWhy
IDMatchIndonesia, alpha-2Try →
USMatchUnited States, alpha-2Try →
GBMatchUnited Kingdom, alpha-2Try →
usNo matchlowercase — uppercase firstTry →
USANo matchalpha-3 — needs the {3} variantTry →
US1No matchdigits do not belong in alpha codesTry →

Where to use it

JavaScript (shape + membership)

const isShape = /^[A-Z]{2}$/.test('ID');            // true: looks like a code
const COUNTRIES = new Set(['ID', 'US', 'GB', 'DE']); // real members
const real = COUNTRIES.has('ID');                     // true

Python

import re
SHAPE = r'^[A-Z]{2}$'
assert SHAPE.fullmatch('ID')
# membership: pycountry, or your own dict of ~249 ISO 3166-1 codes

BigQuery (RE2)

SELECT country_code,
       REGEXP_CONTAINS(country_code, r'^[A-Z]{2}$') AS shape_ok
FROM project.dataset.countries

Common mistakes

Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
Open the regex tester →

FAQ

How do I check a real ISO 3166 country code?

Two steps: shape (^[A-Z]{2}$) then membership — a Set or array of the 249 assigned codes, or a package like pycountry. Regex alone cannot know that QQ is unassigned.

What is the difference between alpha-2, alpha-3 and numeric codes?

alpha-2 = 2 letters (ID), alpha-3 = 3 letters (IDN), numeric = 3 digits (360). Three shapes, three tiny regexes — pick the one your data source actually emits.

Does GA4 store country codes?

GA4 stores full country names in its country dimension. Convert names to alpha-2 with a lookup table before pattern-matching; keep the join in SQL, not in the regex.

IBAN Regex — Validate International Bank Account Numbers · Phone Number Regex — International & US Formats · UTM Parameter Regex — Match & Extract utm_* Tags

For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.