title: Why is regex search in substring "not completely equivalent to slicing the string" in Python?
body: <p>As the <a href="https://docs.python.org/3.5/library/re.html#re.regex.search" rel="nofollow noreferrer">documentation</a> stated, using <code>regex.search(string, pos, endpos)</code> is not completely equivalent to slicing the string, i.e. <code>regex.search(string[pos:endpos])</code>. It won't do regex matching <em>as if</em> the string is starting from <code>pos</code>, so <code>^</code> does not match the beginning of the <em>substring</em>, but only matches the real beginning of the whole string. However, <code>$</code> matches either the end of the substring or the whole string.</p>
  
  <pre><code>    &gt;&gt;&gt; re.compile('^am').findall('I am falling in code', 2, 12)
      []        # am is not at the beginning
      &gt;&gt;&gt; re.compile('^am').findall('I am falling in code'[2:12])
      ['am']    # am is the beginning
      &gt;&gt;&gt; re.compile('ing$').findall('I am falling in code', 2, 12)
      ['ing']   # ing is the ending
      &gt;&gt;&gt; re.compile('ing$').findall('I am falling in code'[2:12])
      ['ing']   # ing is the ending
  
      &gt;&gt;&gt; re.compile('(?&lt;= )am').findall('I am falling in code', 2, 12)
      ['am']    # before am there is a space
      &gt;&gt;&gt; re.compile('(?&lt;= )am').findall('I am falling in code'[2:12])
      []        # before am there is no space
      &gt;&gt;&gt; re.compile('ing(?= )').findall('I am falling in code', 2, 12)
      []        # after ing there is no space
      &gt;&gt;&gt; re.compile('ing(?= )').findall('I am falling in code'[2:12])
      []        # after ing there is no space
  
      &gt;&gt;&gt; re.compile(r'\bm.....').findall('I am falling in code', 3, 11)
      []
      &gt;&gt;&gt; re.compile(r'\bm.....').findall('I am falling in code'[3:11])
      ['m fall']
      &gt;&gt;&gt; re.compile(r'.....n\b').findall('I am falling in code', 3, 11)
      ['fallin']
      &gt;&gt;&gt; re.compile(r'.....n\b').findall('I am falling in code'[3:11])
      ['fallin']
  </code></pre>
  
  <p>My questions are... Why is it not consistent between <em>beginning</em> and <em>ending</em> match? Why does using <code>pos</code> and <code>endpos</code> treat the <em>end</em> as the real end, but the <em>start/beginning</em> is not treated as the real start/beginning? </p>
  
  <p>Is there any approach to make using <code>pos</code> and <code>endpos</code> imitate slicing? Because Python <a href="https://stackoverflow.com/a/5722068/1197317">copies string when slicing</a> instead of just reference the old one, it would be more efficient to use <code>pos</code> and <code>endpos</code> instead of slicing when working with big string multiple times.</p>