URL Slug Regex

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

Validate URL-friendly slugs. Allows lowercase letters, numbers, and hyphens (not at start/end).

Test This Pattern →

Pattern Breakdown

Understanding the regex pattern ^[a-z0-9]+(?:-[a-z0-9]+)*$:

  • ^ - Start of string
  • $ - End of string
  • ? - Optional (zero or one)
  • + - One or more
  • * - Zero or more
  • [...] - Character class
  • (...) - Capturing group
  • (?:...) - Non-capturing group

Examples

Input Result Explanation
my-blog-post ✓ Match Valid slug
post-123 ✓ Match Slug with numbers
-invalid-slug ✗ No Match Starts with hyphen
Has Spaces ✗ No Match Contains spaces

Code Examples

JavaScript

JavaScript
const pattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const text = "my-blog-post";

// Test if string matches
if (pattern.test(text)) {
  console.log("Valid!");
}

// Extract matches
const matches = text.match(pattern);
console.log(matches);

Python

Python
import re

pattern = r'^[a-z0-9]+(?:-[a-z0-9]+)*$'
text = "my-blog-post"

# Test if string matches
if re.match(pattern, text):
    print("Valid!")

# Find all matches
matches = re.findall(pattern, text)
print(matches)

PHP

PHP
<?php
$pattern = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
$text = "my-blog-post";

// Test if string matches
if (preg_match($pattern, $text)) {
    echo "Valid!";
}

// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>

Java

Java
import java.util.regex.*;

String pattern = "^[a-z0-9]+(?:-[a-z0-9]+)*$";
String text = "my-blog-post";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);

if (m.matches()) {
    System.out.println("Valid!");
}

Use Cases

Common applications: CMS systems, blog platforms, SEO-friendly URLs

Frequently Asked Questions

What is the regex pattern for url slug regex?
The regex pattern is: ^[a-z0-9]+(?:-[a-z0-9]+)*$. Validate URL-friendly slugs. Allows lowercase letters, numbers, and hyphens (not at start/end).
How do I use the url slug regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^[a-z0-9]+(?:-[a-z0-9]+)*$'); or const regex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^[a-z0-9]+(?:-[a-z0-9]+)*$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for url slug regex?
CMS systems, blog platforms, SEO-friendly URLs

Related Regex Patterns

More Regex Tools

GetDevUtils offers a suite of developer tools including: