RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex for a URL slug

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

Lowercase alphanumeric groups joined by single hyphens. Written this way a leading hyphen, a trailing hyphen and a doubled hyphen are all impossible, which is cleaner than testing for each of them afterwards.

What each part does

[a-z0-9]+a group of lowercase letters or digits
(-[a-z0-9]+)*any number of hyphen-plus-group repetitions

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
hellomatcheshello
hello-worldmatcheshello-world
post-42matchespost-42
Hellono match
-hellono match
hello-no match
hello--worldno match
hello_worldno match

The mistake to avoid

Generating the slug and validating it with different rules. Slugify from the same table you validate against, or you will produce values your own check rejects.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers