Concept
Alternation with the | Operator
The pipe | matches either the expression on its left or on its right. Combine with groups to alternate over a subpattern.
Basic alternation
cat|dog matches the string 'cat' or the string 'dog.' The alternatives are tried left-to-right, and the first match wins. Alternation has the LOWEST precedence in regex — everything to the left of the | and everything to the right are treated as separate branches.
Group to scope the alternation
Without parentheses, ^cat|dog$ means '^cat at the start OR dog$ at the end' — not what you'd expect. Wrap the alternatives: ^(cat|dog)$ matches either whole-string cat or whole-string dog.
Order affects what matches
Regex engines try branches left-to-right and stop at the first success. With 'cat|cats' on the input 'cats,' the engine matches 'cat' — the shorter branch wins because it comes first. Put longer/more specific alternatives first when that matters.
When to prefer a character class
For single-character alternatives, [abc] is faster and clearer than (a|b|c). Use | for multi-character branches or when alternatives have different lengths.
Related patterns
IPv4 Address
Match valid IPv4 addresses with each octet constrained to 0–255.
/(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)…/gHTTP Status Code
Match 3-digit HTTP status codes in the 1xx–5xx range.
/\b[1-5]\d{2}\b/gLog Level
Matches standard log level keywords in log lines.
/\b(TRACE|DEBUG|INFO|WARN|ERROR|FAT…/g12-Hour Time with AM/PM
Match 12-hour time formats with AM or PM suffix — e.g. 9:30 AM, 11:45:15 pm.
/(?:0?[1-9]|1[0-2]):[0-5]\d(?::[0-5…/g