Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex for URL slug
Regex pattern · validation

Regex for URL slug

Regex for URL slug: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^[a-z0-9]+(?:-[a-z0-9]+)*$/ as a URL slug regex. It matches "my-blog-post" and "post-2026", and rejects "My-Post" and "my--post". To create slugs from titles, use the slug generator rather than validating after the fact.

Last updated · Maintained by FreeAIToolz · How we test

/^[a-z0-9]+(?:-[a-z0-9]+)*$/
  • my-blog-postmatches
  • post-2026matches
  • amatches
  • My-Postno match
  • my--postno match
  • -my-postno match
  • my-post-no match
  • my_postno match
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^[a-z0-9]+starts with lowercase letters or digits
(?:-[a-z0-9]+)*$any number of single hyphens, each followed by more letters or digits

Examples

InputResult
my-blog-post✓ Matches
post-2026✓ Matches
a✓ Matches
My-Post✗ No match
my--post✗ No match
-my-post✗ No match
my-post-✗ No match
my_post✗ No match

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

To create slugs from titles, use the slug generator rather than validating after the fact.

When to use this pattern

CMS and e-commerce URL fields, so every slug is lowercase, hyphenated and SEO-friendly.

Use it in your language

JavaScript

const re = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
re.test(input); // true or false

Python

import re
pattern = re.compile(r'^[a-z0-9]+(?:-[a-z0-9]+)*$')
bool(pattern.search(value))

PHP

$ok = preg_match('~^[a-z0-9]+(?:-[a-z0-9]+)*$~', $value) === 1;

Java

Pattern pattern = Pattern.compile("^[a-z0-9]+(?:-[a-z0-9]+)*$");
boolean ok = pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^[a-z0-9]+(?:-[a-z0-9]+)*$`)
ok := re.MatchString(value)

More regex patterns

Frequently asked questions

What is the regex for URL slug?
/^[a-z0-9]+(?:-[a-z0-9]+)*$/. To create slugs from titles, use the slug generator rather than validating after the fact.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
Why does the pattern start with ^ and end with $?
They anchor the match to the whole string, so "abcmy-blog-postxyz" cannot pass just because it contains a valid part. To search for matches inside longer text, remove ^ and $ (use \b where word boundaries help) and add the g flag.