How do you match one of two words in a regular expression?
Developers often encounter situations where they need to validate input that accepts either a shorthand token or its full textual equivalent. A common scenario involves checking for an email handle like @ or the literal word at. When attempting this with a pattern like /@?(at)?/, the result is almost invariably incorrect. The confusion stems from a fundamental misunderstanding of how regex quantifiers and grouping interact, specifically regarding the optional nature of the first character versus the entire second group.
In the pattern /@?(at)?/, the ? following @ makes the at-sign optional, while the ? following the group (at) makes the whole word "at" optional. However, because the first part @? can match an empty string (zero occurrences), the regex engine often satisfies the condition by matching nothing at all, or it matches just "at" without ever checking for a standalone @ in contexts where you might expect specific boundaries. More critically, this pattern fails to distinguish between the two distinct choices effectively because the first choice itself is treated as optional rather than mutually exclusive from the second.
To correctly match either a specific character like @ or a specific word like at, you must use alternation with the pipe operator (|). This operator explicitly tells the engine: "Match one of these paths, and stop after finding the first valid one." The correct pattern becomes /(@|at)/. Here, the regex engine attempts to match @ first. If that succeeds, it stops. If that fails (for instance, if the input string starts with a letter), it backtracks and tries the second alternative, at.
Consider a practical implementation in PHP using the preg_match function:
$pattern = '/(@|at)/';
$string1 = 'This is an @ symbol';
$string2 = 'She said "at" that time';
$string3 = 'Neither matches here';
// Match for string1
if (preg_match($pattern, $string1, $matches)) {
echo "Matched: " . $matches[0] . PHP_EOL; // Outputs: @
}
// Match for string2
if (preg_match($pattern, $string2, $matches)) {
echo "Matched: " . $matches[0] . PHP_EOL; // Outputs: at
}
This approach ensures that the two options are treated as distinct alternatives rather than nested optionalities. It is also important to consider word boundaries if you intend to match the word at only when it stands alone and not as part of a larger word like attack. In such cases, adding \b (word boundary) anchors prevents false positives:
$pattern = '/(@|\bat)/'; // Matches @ or the word "at" surrounded by non-word characters
If your application stack is built on Laravel, you might utilize regular expressions within form validation rules or custom validator callbacks. While Laravel does not have a built-in rule for regex alternation in its validate method syntax directly without passing a closure or string pattern, you can define a custom rule:
use Illuminate\Validation\Rule;
$validated = $request->validate([
'handle' => [
Rule::required(),
Rule::regex('/^(@|at)$/i') // Case insensitive match for either value
]
]);
One common pitfall in this area is the assumption that ? creates a choice. It does not; it creates optionality. Using @|at is the explicit way to say "choose one," whereas @? says "optionally have an @." The latter allows zero matches, which usually breaks strict validation logic where you expect exactly one of the options to be present.
Another consideration is performance. While regex engines are highly optimized, extremely long alternations at the start of a pattern can sometimes lead to catastrophic backtracking if not structured correctly. However, for a simple two-option list like (@|at), this is negligible. The primary concern remains clarity and intent: using | makes it immediately obvious to future maintainers that these are mutually exclusive choices, avoiding ambiguity inherent in nested optional groups.