Regex for Validating a URL Slug
Matches a lowercase, hyphen-separated URL-safe string.
Published October 12, 2026
This regex checks that a slug uses lowercase letters, digits and single hyphens, with no leading or trailing hyphen.
How the pattern works
Breaking the pattern down: [a-z0-9]+ = a word; (?:-[a-z0-9]+)* = more hyphen-separated words.
Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.
Pattern tests
/^[a-z0-9]+(?:-[a-z0-9]+)*$/
✓ 'hello-world'
✓ 'post-42'
✗ 'Hello-World'
✗ '-start'
Practical examples
The pattern
const re = /^[a-z0-9]+(?:-[a-z0-9]+)*$/Test it
const re = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
re.test('hello-world') // true
re.test('post-42') // true
re.test('Hello-World') // false
re.test('-start') // falseIn Python
import re
re.search(r'^[a-z0-9]+(?:-[a-z0-9]+)*$', text)Common mistakes
- Allowing double hyphens.
- Uppercase letters.
- Non-ASCII titles without transliteration.
Key takeaways
- Anchors (^ and $) make the whole string match instead of a part of it.
- Regex checks format only; verify data separately when it matters.
- Test with valid and invalid samples.
FAQ
Create slugs from titles?
Lowercase, replace non-alphanumerics with hyphens, trim hyphens.
Where can I test this pattern?
Use the Regex Tester on this site, or regex101.com.