Regex Patterns Developers Reuse Every Week
Regular expressions are compact, but that compactness can hide assumptions. The most reliable patterns start with a plain-language rule and are tested with examples that must pass and fail.
Write the rule in words first
Before writing a pattern, state exactly what is allowed: characters, length, separators, and whether the whole value must match. For a slug, that might be lowercase letters, numbers, and single hyphens between words; it is not simply “letters and hyphens”.
This step prevents a common mistake: using a partial match when a field needs whole-value validation. Anchors such as ^ and $ matter when the complete string must meet the rule.
Test positive and negative examples
A pattern that matches one good example has not yet been validated. Include boundary lengths, empty input, whitespace, punctuation, Unicode text where relevant, and values that contain a valid fragment inside an invalid larger string.
- List examples that should match and examples that must not.
- Run them with the same flags and runtime used by the application.
- Add edge cases whenever a production issue reveals an assumption.
Use regex only for the right layer
Regex is useful for shape validation and finding text, but it is not a substitute for semantic checks. An email-shaped string may not belong to a user, and a UUID-shaped value may not identify an existing record. Keep business validation in application logic.