Skip to content

Regex for Slug — Pattern, Examples & Caveats

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

This pattern validates a URL slug: lowercase letters and digits grouped into words separated by single hyphens, with no leading, trailing or consecutive hyphens. Slugs are the human-readable, SEO-friendly part of a URL path. Web patterns deal with markup, styling and web identifiers: HTML tags and comments, CSS colors, Markdown links, slugs and source-code comments. They are handy for quick scanning and lightweight transforms, but markup is not a regular language, so anything structural or security-sensitive should use a real parser (DOM, CSS or Markdown) rather than regex alone. It needs no special flags. Apply it to the whole input as a format contract. It is lowercase-only; uppercase or Unicode slugs need a different pattern or normalization first. To generate a slug from arbitrary text, lowercase it, replace non-alphanumeric runs with hyphens, then trim hyphens — validation alone does not transform. Reserved words and length limits are application concerns the regex cannot enforce. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • ^ — start anchor
  • [a-z0-9]+ — first word of lowercase alphanumerics
  • (?:-[a-z0-9]+)* — zero or more hyphen-separated words
  • - — a single literal hyphen between words
  • $ — end anchor

What it matches

hello-worldmy-first-postcron-every-5-minutesabc123

What it does not match

Hello-World-leadingtrailing-double--hyphenunder_scorehas space

When to use it

Reach for a web pattern for quick scanning and lightweight transforms of markup, styling and web identifiers: locating tags, comments, colors, slugs or Markdown links. For anything structural or security-sensitive — parsing a DOM, sanitizing HTML, rewriting CSS — use a real parser or a proven library instead, because markup is not a regular language and regex-based handling is a frequent source of bugs and cross-site scripting bypasses.

Caveats

  • It is lowercase-only; uppercase or Unicode slugs need a different pattern or normalization first.
  • To generate a slug from arbitrary text, lowercase it, replace non-alphanumeric runs with hyphens, then trim hyphens — validation alone does not transform.
  • Reserved words and length limits are application concerns the regex cannot enforce.

Code examples

JavaScript
const re = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const input = "hello-world";
if (re.test(input)) {
  // valid: proceed
} else {
  // reject with a helpful message
}
Python
import re

rx = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$")
value = "hello-world"
if rx.fullmatch(value):
    pass  # valid
else:
    raise ValueError("invalid format")
Java
import java.util.regex.*;

Pattern p = Pattern.compile("^[a-z0-9]+(?:-[a-z0-9]+)*$");
Matcher m = p.matcher("hello-world");
boolean ok = m.matches();   // whole input must conform
PHP
<?php
$subject = "hello-world";
if (preg_match('/^[a-z0-9]+(?:-[a-z0-9]+)*$/', $subject, $m)) {
    // $m[0] is the full match
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

How do I turn a title into a slug?

Lowercase the title, replace every run of non-alphanumeric characters with a single hyphen, then strip leading/trailing hyphens. Validate the result with this pattern.

Why forbid consecutive hyphens?

Double hyphens look like mistakes and create ambiguous URLs. The (?:-[a-z0-9]+)* structure requires a non-empty word after each hyphen, so -- is rejected.

When should I avoid regex for web content?

For parsing HTML, CSS or Markdown structure, use a real parser. Regex cannot handle nesting, quoted delimiters or malformed markup reliably, and regex-based sanitization is a common source of XSS bypasses.

Why is regex HTML sanitization dangerous?

HTML has nested, quoted and malformed constructs that regex mis-parses, so attackers hide scripts in forms the pattern misses. Always sanitize with a proven library (DOMPurify) or a real parser, never ad-hoc regex.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →