Match and validate URL-friendly slugs using regex. Ensures lowercase letters, digits, and hyphens only, with no leading or trailing hyphens.
/^[a-z0-9]+(?:-[a-z0-9]+)*$/| Token | Meaning |
|---|---|
^ | Start of string |
[a-z0-9]+ | One or more lowercase letters or digits |
(?:-[a-z0-9]+)* | Zero or more groups of a hyphen followed by lowercase letters/digits |
$ | End of string |
hello-worldMatchmy-blog-post-123MatchsimpleMatcha-b-cMatchHello-WorldNo match-leading-hyphenNo matchtrailing-hyphen-No matchdouble--hyphenNo matchconst slugRegex = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const slug = "my-blog-post-123";
const isValid = slugRegex.test(slug);
console.log(isValid); // trueimport re
slug_regex = r'^[a-z0-9]+(?:-[a-z0-9]+)*$'
slug = "my-blog-post-123"
is_valid = bool(re.match(slug_regex, slug))
print(is_valid) # TrueWant to test this pattern with your own data?
Try this pattern in Regex Tester →