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.
| Input | Result | Matched |
|---|---|---|
| hello | matches | hello |
| hello-world | matches | hello-world |
| post-42 | matches | post-42 |
| Hello | no match | — |
| -hello | no match | — |
| hello- | no match | — |
| hello--world | no match | — |
| hello_world | no 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 RegexBuilderOther regex answers
- Regex for an email address
- Regex for a US phone number
- Regex for an IPv4 address
- Regex for a URL
- Regex for a date in YYYY-MM-DD format
- Regex to match digits only
- Regex for alphanumeric characters
- Regex to find special characters
- Regex for a strong password
- Regex to match whitespace
- Regex to trim leading and trailing whitespace
- Regex for a UUID