Slug regex

Regex to validate URL slugs: lowercase letters and digits separated by single hyphens. Plus how to generate one.

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

Matches

  • hello-world
  • regex-101
  • a

Doesn't match

  • Hello-World
  • hello--world
  • -hello
  • hello_world

Notes

  • To create a slug: lower-case, replace /[^a-z0-9]+/g with "-", then trim hyphens with /^-|-$/g.
  • The case converter has a kebab-case mode that does this for you.

Code

JavaScript

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

Python

import re

bool(re.fullmatch(r'[a-z0-9]+(?:-[a-z0-9]+)*', value))

Try it on your own input

The live tester adds the g and m flags so every line is checked separately.

Questions

How do I allow underscores?

Use [a-z0-9]+(?:[-_][a-z0-9]+)*.

More patterns

Email regexPhone number regexURL regexIP address regexDate regexTime regex (24-hour and 12-hour)UUID regexHex color regex