title: Regex to swap A and B in multiline text, with a various number of occurrences of A or B
body: <p>I have a multiline text, in which I want to swap the names of Leibniz and Newton :</p>
  
  <pre><code>1) Either Leibniz or Newton or both have invented calculus.
  
  2) Newton claimed he was the first.
  
  3) Newton lived in England, and Leibniz lived in Germany.
  
  4) Leibniz and Newton are the same person, said Leibniz.. 
  
  5) Leibniz and Newton are not the same person, said Newton about Leibniz.
  </code></pre>
  
  <p>So I created (with help of examples in S.O.) the following regex :</p>
  
  <pre><code>(Leibniz|Newton)(.+)(Leibniz|Newton)
  </code></pre>
  
  <p>to be replaced with</p>
  
  <pre><code>$3$2$1
  </code></pre>
  
  <p>The result is that the names are swapped in lines 1 and 3 only :</p>
  
  <pre><code>1) Either Newton or Leibniz or both have invented calculus. (OK)
  
  2) Newton claimed he was the first. 
  
  3) Leibniz lived in England, and Newton lived in Germany. (OK)
  
  4) Leibniz and Newton are the same person, said Leibniz.. 
  
  5) Leibniz and Newton are not the same person, said Newton about Leibniz.
  </code></pre>
  
  <p>Where did I go wrong ? I only understand that my regex works only if the lines contain one A AND one B, but not if there are less (0) or more (2, 3, etc...) occurrences of A OR B.</p>
  
  <p>I would be very grateful for a small explanation (if it is not a chore).</p>
  
  <p>Thanks in advance</p>