Regex exactly n OR m times

Regex exactly n OR m times

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

The Limitations of {n,m} and Why We Need Alternation for Exact Counts

When designing validation rules or parsing logic, there is a frequent need to enforce strict repetition counts. A common question arises when dealing with two specific scenarios: requiring an element X to appear exactly n times, or exactly m times, but no other quantity. The intuitive approach suggests combining quantifiers. If you look at the pattern X{n,m}, it matches X between n and m times inclusively. This is useful for ranges, but it fails when the requirement is strict: either n or m, never anything in between.

The standard solution to enforce exact counts within a regex engine is the alternation operator (|). The pattern X{n}|X{m} explicitly asserts that the string must contain X repeated exactly n times, OR it must contain X repeated exactly m times. This constructs a union of two distinct sets of valid strings. For example, if X is a digit and you need exactly 3 digits or exactly 5 digits, the regex d{3}|d{5} correctly rejects dd (2 times), ddd (3 times - wait, that's included in the first alternative), dddd (4 times), and ddddd (5 times). The critical distinction here is that the quantifier {n} enforces an exact count, whereas {n,m} creates a range. Combining them with alternation is the only way to maintain the "exactness" of both constraints simultaneously without creating a gap between the counts.

Implementation in PHP and Laravel

In practical development, particularly within the Laravel ecosystem, this concept translates directly into validation rules or custom string matching logic. While Laravel's built-in Rule interface offers powerful methods like min, max, and size, it does not provide a native method to say "exactly 3 OR exactly 5". You often end up writing custom validators.

Consider a scenario where you are validating a code snippet that must be either 4 characters long or 6 characters long, such as specific legacy identifiers. Using the regex pattern directly in a validation rule is efficient:

use Illuminate\Support\Facades\Validator;

$validator = Validator::make(
    ['code' => 'abcd'],
    [
        'code' => 'regex:/^.{4}|.{6}$/',
    ]
);

If you pass 1234, the validation passes. If you pass 123, it fails. If you pass 12345, it fails. The alternation ensures that the length is strictly one of the two allowed options. This approach avoids writing a custom callback unless the logic becomes significantly more complex, such as needing to match specific content within those lengths rather than just counting characters.

Trade-offs and Performance Considerations

While X{n}|X{m} is logically sound, it introduces complexity in how regex engines process the input. When an engine encounters an alternation like A|B, it typically tries the left branch first. If X{n} matches, the engine stops searching for X{m}. This is generally efficient because matching a fixed count is linear time relative to the number of characters scanned.

However, performance degrades if the pattern is nested or used in a loop context where backtracking occurs. For instance, if you have a pattern like (ab){3}|(ab){5}, the engine must verify that the input ends exactly after the third pair before attempting the fifth. If the input is ababababc, the engine matches the first three pairs, sees that the string hasn't ended (due to the trailing c), and then backtracks or fails depending on anchoring.

It is crucial to anchor your regex pattern. Without anchors (^ and $), the pattern X{n}|X{m} will match a substring within a larger string. For example, in the string "abcdeeee", the pattern e{3} matches "eee". If you intend to validate an entire token or field, failing to anchor the pattern can lead to false positives where only part of the data satisfies the count requirement.

Why Not {n,m}?

A common pitfall is attempting to simplify X{n}|X{m} into X{n,m}. This transformation is mathematically incorrect for exact matching requirements. The set represented by {n,m} includes all integers $k$ where $n \le k \le m$. If $n=3$ and $m=5$, the pattern X{3,5} accepts strings with 3, 4, or 5 repetitions of X. This violates the "exactly" constraint because it permits the intermediate count (4) which the original requirement explicitly excludes. Relying on range quantifiers for exclusive exact counts is a logical error that leads to silent data corruption in validation layers.

For complex scenarios involving multiple distinct lengths, such as allowing 4 characters OR 6 characters OR 8 characters, the pattern naturally extends: X{4}|X{6}|X{8}. While this increases the regex size linearly with the number of options, it remains readable and performant for a small number of alternatives. If you find yourself needing to match an arbitrary large set of exact lengths, it may be worth reconsidering whether a list-based validation rule in your application logic (checking length against an allowed array) is more maintainable than constructing a massive alternation chain.

Our network