title: Regex for multiline string literals produces `StackOverflowError`
body: <p>I want to match strings enclosed in triple <code>"</code>-quotes which may contain line breaks, and which don't contain any <code>"""</code>-substrings except at the very beginning and in the very end.</p>
  
  <p>Valid example:</p>
  
  <pre><code>"""foo
  bar "baz" blah"""
  </code></pre>
  
  <p>Invalid example:</p>
  
  <pre><code>"""foo bar """ baz"""
  </code></pre>
  
  <p>I tried using the following regex (as Java <code>String</code> literal):</p>
  
  <pre><code>"(?m)\"\"\"(?:[^\"]|(?:\"[^\"])|(?:\"\"[^\"]))*\"\"\""
  </code></pre>
  
  <p>and it seems to work on short examples. However, on longer examples, like on a string consisting of thousand lines with <code>hello world</code>, it gives me a <code>StackOverflowError</code>.</p>
  
  <p><strong>Scala snippet to reproduce the error</strong></p>
  
  <pre><code>import java.util.regex.{Pattern, Matcher}
  
  val text = "\"" * 3 + "hello world \n" * 1000 + "\"" * 3
  val p = Pattern.compile("(?m)\"\"\"(?:[^\"]|(?:\"[^\"])|(?:\"\"[^\"]))*\"\"\"")
  println(p.matcher("\"\"\" foo bar baz \n baz bar foo \"\"\"").lookingAt())
  println(p.matcher(text).lookingAt())
  </code></pre>
  
  <p>(note: test locally, Scastie times out; or maybe reduce 1000 to smaller number?).</p>
  
  <p><strong>Java snippet that produces the same error</strong></p>
  
  <pre><code>import java.util.regex.Pattern;
  import java.util.regex.Matcher;
  
  class RegexOverflowMain {
    public static void main(String[] args) {
      StringBuilder bldr = new StringBuilder();
      bldr.append("\"\"\"");
      for (int i = 0; i &lt; 1000; i++) {
        bldr.append("hello world \n");
      }
      bldr.append("\"\"\"");
      String text = bldr.toString();
      Pattern p = Pattern.compile("(?m)\"\"\"(?:[^\"]|(?:\"[^\"])|(?:\"\"[^\"]))*\"\"\"");
      System.out.println(p.matcher("\"\"\" foo bar baz \n baz bar foo \"\"\"").lookingAt());
      System.out.println(p.matcher(text).lookingAt());
    }
  }
  </code></pre>
  
  <p><strong>Question</strong></p>
  
  <p>Any idea how to make this "stack safe", i.e. can someone find a regex that accepts the same language, but does not produce a <code>StackOverflowError</code> when fed to the Java regex API?</p>
  
  <p>I don't care whether the solution is in Scala or Java (or whatever), as long the same underlying Java regex library is used.</p>