title: How can I search for a Regular Expression match that begins before a certain index of a string?
body: <p>Let's say I have a regular expression</p>
  
  <pre><code>let regexString = "\\s{1,3}(---+)\\s*"
  let regex = try? NSRegularExpression(pattern: regexString)
  </code></pre>
  
  <p>and a string</p>
  
  <pre><code>let string = "Space --- the final frontier --- these are the voyages..."
  </code></pre>
  
  <p>and let's further assume that the string was <em>really</em> long and continued after the ellipses (<code>...</code>) over several thousands of characters.</p>
  
  <p>Now I want to find the first match for the regular expression <code>regex</code>, but I want to <strong>stop searching after a certain index</strong> for efficiency reasons.</p>
  
  <h3>Example:</h3>
  
  <pre><code>index:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
  string: S  p  a  c  e     -  -  -     t  h  e     f  i  n  a  l     f  r  o  n  t  i  e  r
  range:  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  ⬆︎ -  -  -  -  -  -  -  -  -  -  -  -
                                                       max 
  </code></pre>
  
  <p>This would mean that I only search the string for a regular expression match <strong>that <em>starts</em> before index 15</strong>.</p>
  
  <hr>
  
  <p>The behavior described above is different from searching only a subrange of the string. Here's why:</p>
  
  <h3>✅ Should match:</h3>
  
  <p>The following example should produce a match at range [5–9], because the match starts before the max index (= 7).</p>
  
  <pre><code>index:  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
  string: S  p  a  c  e     -  -  -     t  h  e     f  i  n  a  l     f  r  o  n  t  i  e  r
  range:  +  +  +  +  +  +  +  ⬆︎ -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -  -
                               max 
  </code></pre>
  
  <h3>❎ Should, but would not match:</h3>
  
  <p>If I only searched a substring up to the max index (= 7), the regular expression would not be able to match because part of the match would be truncated.</p>
  
  <pre><code>index:  0  1  2  3  4  5  6  7  
  string: S  p  a  c  e     -  -  
  range:  +  +  +  +  +  +  +  ⬆︎ 
                               max 
  </code></pre>
  
  <p><strong>How can I achieve this?</strong></p>