RegexCraft

URL slug regex

Validates a URL slug: lowercase letters and digits in words joined by single hyphens, with no leading, trailing or doubled hyphen. The m flag tests each line of the text separately.

Open in the tester

The pattern

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

Sample text, 3 matches

hello-world regex-101 Bad_Slug -leading-dash double--dash ok

What it deliberately doesn’t do

  • Uppercase and non-ASCII letters are rejected; slugify the title first.

Explained, in order

  1. ^Start anchor — asserts position at the beginning of the string (or line with the 'm' flag). Consumes no characters.
  2. [a-z0-9]Character class — matches one character from: 'a' through 'z', '0' through '9'
  3. +The preceding element matches one or more times (greedy)
  4. (?:-[a-z0-9]+)Non-capturing group — groups the pattern without capturing
  5. -Matches the character '-' literally
  6. [a-z0-9]Character class — matches one character from: 'a' through 'z', '0' through '9'
  7. +The preceding element matches one or more times (greedy)
  8. *The preceding element matches zero or more times (greedy)
  9. $End anchor — asserts position at the end of the string (or line with the 'm' flag). Consumes no characters.

In your language

JavaScript

The engine this page was tested with.

const re = /^[a-z0-9]+(?:-[a-z0-9]+)*$/gm;

// Example
const matches = [...str.matchAll(/^[a-z0-9]+(?:-[a-z0-9]+)*$/gm)];
for (const m of matches) {
  console.log(m[0], m.index, m.groups);
}

Python

Translated. Named groups are rewritten to (?P<name>…).

import re

pattern = re.compile(r"^[a-z0-9]+(?:-[a-z0-9]+)*$", re.MULTILINE)

# Example
for m in pattern.finditer(text):
    print(m.group(0), m.start(), m.groups())

Go

Translated. Go's RE2 has no lookaround or backreferences.

package main

import (
	"fmt"
	"regexp"
)

// Note: Inline flags at the start of the pattern: (?i), (?m), (?s).

var re = regexp.MustCompile(`(?m)^[a-z0-9]+(?:-[a-z0-9]+)*$`)

func main() {
	for _, match := range re.FindAllStringSubmatch(text, -1) {
		fmt.Println(match[0], match)
	}
}

Rust

Translated. The regex crate has no lookaround or backreferences.

use regex::Regex;

// Note: Rust finds all matches via find_iter / captures_iter (no 'g' flag).
// Note: Use (?s), (?m), (?u) inline flags or the RegexBuilder API.

fn main() {
    let re = Regex::new(r#"(?m)^[a-z0-9]+(?:-[a-z0-9]+)*$"#).unwrap();

    for m in re.find_iter(text) {
        println!("{} at {}", m.as_str(), m.start());
    }
}