regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Match a URL Slug

Copy the pattern, type a candidate below, and see whether it is a valid slug. Below the tester: the rules it enforces and how to allow underscores.

Regex pattern

/^[a-z0-9]+(?:-[a-z0-9]+)*$/

This matches a URL slug of lowercase letters and digits with single hyphens between segments, e.g. my-blog-post. It rejects uppercase, spaces, underscores and leading, trailing or doubled hyphens.

/ /

What this pattern matches

This matches a clean URL slug: lowercase letters and digits, with single hyphens between words and no leading, trailing, or doubled hyphens.

How it works, part by part

^[a-z0-9]+ — the slug must start with one or more lowercase letters or digits.

(?:-[a-z0-9]+)* — zero or more groups of a single hyphen followed by more characters.

$ — and nothing else to the end.

Allowing underscores or uppercase

Add _ to the character classes to allow underscores, or add A-Z to accept uppercase — though lowercase-only slugs are the SEO-friendly convention.

Use it in your code

Python
import re
text = "my-first-post"
pattern = r'''^[a-z0-9]+(?:-[a-z0-9]+)*$'''
for m in re.finditer(pattern, text):
    print(m.group())
JavaScript
const text = "my-first-post";
const re = new RegExp(String.raw`^[a-z0-9]+(?:-[a-z0-9]+)*$`, "g");
console.log(text.match(re));

FAQ

Does it reject double hyphens?

Yes. Each hyphen must be followed by at least one character, so double-- fails.

Are uppercase letters allowed?

No. The pattern is lowercase-only by design; add A-Z if you must accept them.

Can a slug start with a hyphen?

No. It must begin with a letter or digit, so -leading is rejected.