# Regex for URL Slug Validation

> URL slug regex enforcing lowercase kebab-case with no leading, trailing, or doubled hyphens — the structure explained token by token.

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

A clean URL slug is lowercase words separated by single hyphens: hello-world, post-123. The trick in this pattern is the (?:-[a-z0-9]+)* group — by requiring every hyphen to be followed by at least one character, it rejects leading hyphens, trailing hyphens, and doubles in one stroke, with no lookaheads needed.

## Token by token

| Token | Meaning |
|---|---|
| `^[a-z0-9]+` | the first word: one or more lowercase letters or digits — so no leading hyphen |
| `(?:-` | each following word starts with exactly one hyphen |
| `[a-z0-9]+)` | …followed by at least one character — so no -- and no trailing hyphen |
| `*$` | zero or more of those words, then end of string |

## Examples

- ✓ matches: `hello-world`
- ✓ matches: `post-123`
- ✓ matches: `a`
- ✗ does not match: `Hello-World`
- ✗ does not match: `-hello`
- ✗ does not match: `hello--world`

## Variations

- `^[a-z0-9]+(?:[-_][a-z0-9]+)*$` — also allow underscores as separators
- `^[a-z0-9-]{1,80}$` — loose length-capped form — pair with trim/collapse logic in code

## Language notes

- This validates a slug; to generate one from a title (lowercasing, stripping accents), use a slugify function — see the text-to-slug converter.

## FAQ

### How does this reject double hyphens without a lookahead?

Structure instead of assertion: the string is defined as word (-word)*, and since every word needs at least one character, two hyphens can never be adjacent, and the string can't start or end with one.

### Should slugs allow uppercase?

No — URLs are case-sensitive on most servers, so Hello-World and hello-world would be different pages. Lowercasing at generation time avoids duplicate-content problems and broken links.

## Related patterns

- [Regex for URL Validation](https://www.devkult.com/regex/url.md)
- [Regex for Username Validation](https://www.devkult.com/regex/username.md)
- [Regex for Hex Color Codes](https://www.devkult.com/regex/hex-color.md)

Open the interactive page: https://www.devkult.com/regex/slug