Regex pattern examples: IDs, slugs, versions, and more

Use these regular-expression examples as starting points, then test them against real input and edge cases before production use.

Match the whole value when needed

Anchors matter. ^ matches the start and $ matches the end, so a pattern such as ^[a-z0-9-]+$ ensures the entire value follows the rule. Without anchors, the same expression may match only one acceptable fragment inside a longer invalid string.

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

Keep patterns readable

Break complicated validation into named application rules when possible. A short, testable pattern is safer than a dense expression nobody can maintain. Add examples that should match and examples that must not match.

For a simple semantic version without prerelease tags, ^v?\d+\.\d+\.\d+$ is a useful baseline. Extend it only when your actual input requires more.

^v?\d+\.\d+\.\d+$

Test with representative data

Regex behavior differs across languages and flags. Test line endings, Unicode, empty input, and long strings in the same runtime where the pattern will run.