title: How to match patterns "begins with A or ends with B" with Python regular expression?
body: <pre><code>r'(^|^A)(\S+)(B$|$)'
  </code></pre>
  
  <p>results to matches everything, which actually equals to ^\S$.</p>
  
  <p>How to write one matches "begins with A or ends with B, may both but not neither?"</p>
  
  <p>PS: I also need refer to group (\S+) in the substring module.</p>
  
  <p>Example:</p>
  
  <p>Match <code>Aanything</code>, <code>anythingB</code>, and refer <code>anything</code> group in the replace.</p>