Pattern library / Validation
URL Slug Regex (lowercase-with-hyphens)
A clean URL slug is lowercase letters, digits and single hyphens — no leading/trailing hyphen, no doubled hyphens, no spaces. This pattern enforces all of that in one line, which makes it useful for CMS validation, redirect hygiene checks and crawl audits.
How the pattern works
[a-z0-9]+— one or more core characters, then(-[a-z0-9]+)*— any number of hyphen-separated segments.- The structure inherently forbids leading/trailing/double hyphens: every hyphen must be sandwiched between core characters.
- Underscores? Common in file names, uncommon in URLs — add
_inside the class if your convention uses them. - Non-ASCII slugs (
café-post) need\p{L}(JS/Python with re.UNICODE) — omitted here to stay RE2-portable and strict.
Test it: match & no-match examples
Every row is loaded straight into the tester — click Try to see the match live:
| Input | Result | Why | |
|---|---|---|---|
ga4-regex-cheatsheet | Match | canonical slug | Try → |
post2 | Match | digits allowed | Try → |
GA4-Regex | No match | uppercase rejected | Try → |
-leading | No match | cannot start with hyphen | Try → |
double--hyphen | No match | single hyphens only | Try → |
has space | No match | no spaces | Try → |
Where to use it
JavaScript (slug generator + check)
const slug = title.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, ''); const ok = /^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug);
Python (redirect audit)
import re
SLUG = r'^[a-z0-9]+(-[a-z0-9]+)*$'
broken = [u for u in urls if not SLUG_RE.fullmatch(u.rsplit('/', 1)[-1])]
BigQuery / GA4 (RE2)
REGEXP_CONTAINS(page_path, r'^/[a-z0-9]+(-[a-z0-9]+)+/?$')
Common mistakes
- Generating vs validating: the generator (replace non-slugs with -) is separate — this pattern only judges the result.
- Trailing slash handling — the slug itself must not contain /; check the last path segment, not the whole path.
- Uppercase slugs technically resolve on most servers, but duplicate-content risk makes them worth rejecting.
FAQ
How do I generate a slug then validate it?
Generate: lowercase, replace any run of invalid characters with a single hyphen, trim leading/trailing hyphens. Validate the result with ^[a-z0-9]+(-[a-z0-9]+)*$.
Why does my slug with double hyphens fail?
By design — (-[a-z0-9]+)* requires each hyphen to be followed by core characters, so a--b has an empty segment and fails.
Does this work for full URLs?
No — it validates a single slug segment. For paths, anchor a segment pattern like ^/[a-z0-9]+(-[a-z0-9]+)*/?$ instead.
Related patterns
URL Regex — Match http/https Links (Practical) · Email Validation Regex — Practical Pattern to Test · Remove Query Parameters with Regex (Replace Example)
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.