Advertisement

Pattern library / Validation

Snake Case Regex

Python modules, env vars and database columns share one naming law: lowercase_with_underscores. The pattern enforces it end to end — no leading digit, no double underscore, no uppercase sneaking in — and the notes contrast it with its siblings (kebab, camel) so you pick the right law for the right codebase.

The pattern
^[a-z][a-z0-9]*(_[a-z0-9]+)*$
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
snake_caseMatchcanonical formTry →
my_var2Matchdigits allowed after the first characterTry →
v2_api_keyMatchdigit right after the letter is fineTry →
2_coolNo matchcannot start with a digitTry →
double__underscoreNo matchempty segment between underscoresTry →
kebab-caseNo matchhyphens belong to kebab-caseTry →

Where to use it

JavaScript

const SNAKE = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;
SNAKE.test('api_key_v2');  // true
SNAKE.test('API_KEY');     // false

Python (validate or convert)

import re
SNAKE = r'^[a-z][a-z0-9]*(_[a-z0-9]+)*$'
assert SNAKE.fullmatch('user_id_2')
name = re.sub(r'[^a-z0-9]+', '_', title.lower()).strip('_')  # convert first

BigQuery (RE2)

WHERE REGEXP_CONTAINS(column_name, r'^[a-z][a-z0-9]*(_[a-z0-9]+)*$')

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 convert any string into snake_case?

Lowercase, replace every run of non [a-z0-9] with a single underscore, trim edges: s.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '') — then validate with this pattern.

What is the difference between snake_case and kebab-case?

snake_case uses underscores (user_id); kebab-case uses hyphens (user-id). Identical segment rules, one character apart — kebab is the URL convention covered by the slug pattern.

Why can't a snake_case name start with a digit?

Most languages forbid it (Python: 1var is a syntax error). The ^[a-z] anchor enforces that; drop it only if your field stores free-form keys rather than identifiers.

Slug Regex — Match lowercase-hyphen URL Slugs · SemVer Regex — Match Semantic Versioning (2.0.0) · Email Validation Regex — Practical Pattern to Test

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.