Regex Alternation Precedence – Group OR Patterns with Anchors

Local only

Fix a valid regex where | splits the pattern more broadly than intended and anchors apply to only one side.

7 chars · 1 line

8 chars · 1 line

Pattern did not match the inputFlags: g

Regex grouping behavior

How to fix regex alternation precedence

The valid pattern ^cat|dog$ is parsed as one alternative that starts with cat or another that ends with dog. That is why catfish matches. Group the alternatives when the same anchors should apply to both. This tool is free to use. No account or payment is required.

Last updated

What you can do here

  • Valid regex behavior check
  • Alternation grouping comparison
  • Anchor debugging
  • Match or No match output
  • JavaScript RegExp semantics
  • Browser-local processing

Steps

  1. Split the pattern mentally at each top-level | to see which tokens belong to each branch.
  2. Wrap alternatives in (...) or (?:...) when they must share anchors or surrounding context.
  3. Retest values that previously matched only because one branch was under-anchored.

Alternation can change the scope of anchors

Without grouping, ^cat|dog$ has two branches: ^cat and dog$. Parentheses make the intended common boundaries explicit and easier to review.

Alternation grouping example

Group cat and dog before applying both anchors.

Ambiguous scope

^cat|dog$

Grouped pattern

^(cat|dog)$

Common questions

Frequently asked questions

Why does ^cat|dog$ match catfish?

Because the first alternation branch is ^cat, which only requires cat at the start.

Can I use a non-capturing group?

Yes. ^(?:cat|dog)$ groups the alternatives without creating a capture.

Does | have lower precedence than concatenation?

Yes. Grouping is the clearest way to show exactly which parts belong to each alternative.

Debugging a specific Regex issue? Browse Regex troubleshooting.