title: RegEx Scope of Alternation
body: <p>What is the scope of the alternation operator <code>|</code>? In some cases, it appears that everything to the left of <code>|</code> is one alternative and everything to the right of the <code>|</code> is the second alternative. Why are the alternatives not limited to the capture groups or tokens immediately preceding and following the <code>|</code>?</p>
  
  <p>I am testing with <a href="http://regexr.com/" rel="nofollow noreferrer">RegExr</a>, but I will be running the regular expressions in Java.</p>
  
  <p>I have two short regular expressions:</p>
  
  <pre><code>(\d{3})\W+(SSN)
  </code></pre>
  
  <p>(Matches in bold.)</p>
  
  <p>SSNx <strong>123 SSN</strong></p>
  
  <pre><code>(SSN)\W+(\d{3})
  </code></pre>
  
  <p>(Matches in bold.)</p>
  
  <p><strong>SSN 123</strong> SSN</p>
  
  <p>If I combine the regular expressions like this:</p>
  
  <pre><code>(\d{3})\W+(SSN)|(SSN)\W+(\d{3})
  </code></pre>
  
  <p>The regular expression matches (in bold)</p>
  
  <p><strong>SSN 123</strong> SSN</p>
  
  <p>SSNx <strong>123 SSN</strong></p>
  
  <p>Why was it unnecessary for me to add parentheses like this?</p>
  
  <pre><code>((\d{3})\W+(SSN))|((SSN)\W+(\d{3}))
  </code></pre>
  
  <p>I expected the alternation operation to alternate only between the surrounding capture groups, e.g. "SSN" OR "SSN". If that were the case, then the results would look like this:</p>
  
  <pre><code>((\d{3})\W+(SSN)\W+(\d{3}))
  </code></pre>
  
  <p>No matches.</p>