Check before matching in order to avoid wasting time.

Change-Id: I3e53e2b01c222b8a8d40a082157f5f8bd95c5a42
Reviewed-on: https://code-review.googlesource.com/32450
Reviewed-by: Paul Wankadia <junyer@google.com>
diff --git a/re2/re2.cc b/re2/re2.cc
index 3f28ba3..89c67ec 100644
--- a/re2/re2.cc
+++ b/re2/re2.cc
@@ -557,7 +557,7 @@
                 Anchor re_anchor,
                 StringPiece* submatch,
                 int nsubmatch) const {
-  if (!ok() || suffix_regexp_ == NULL) {
+  if (!ok()) {
     if (options_.log_errors())
       LOG(ERROR) << "Invalid RE2: " << *error_;
     return false;
@@ -784,6 +784,11 @@
     return false;
   }
 
+  if (NumberOfCapturingGroups() < n) {
+    // RE has fewer capturing groups than number of Arg pointers passed in.
+    return false;
+  }
+
   // Count number of capture groups needed.
   int nvec;
   if (n == 0 && consumed == NULL)
@@ -816,13 +821,6 @@
     return true;
   }
 
-  int ncap = NumberOfCapturingGroups();
-  if (ncap < n) {
-    // RE has fewer capturing groups than number of arg pointers passed in
-    delete[] heapvec;
-    return false;
-  }
-
   // If we got here, we must have matched the whole pattern.
   for (int i = 0; i < n; i++) {
     const StringPiece& s = vec[i+1];
diff --git a/util/pcre.cc b/util/pcre.cc
index 7e1d1ac..cd2d6da 100644
--- a/util/pcre.cc
+++ b/util/pcre.cc
@@ -612,6 +612,11 @@
                        int n,
                        int* vec,
                        int vecsize) const {
+  if (NumberOfCapturingGroups() < n) {
+    // RE has fewer capturing groups than number of Arg pointers passed in.
+    return false;
+  }
+
   assert((1 + n) * 3 <= vecsize);  // results + PCRE workspace
   int matches = TryMatch(text, 0, anchor, true, vec, vecsize);
   assert(matches >= 0);  // TryMatch never returns negatives
@@ -624,10 +629,6 @@
     // We are not interested in results
     return true;
   }
-  if (NumberOfCapturingGroups() < n) {
-    // PCRE has fewer capturing groups than number of arg pointers passed in
-    return false;
-  }
 
   // If we got here, we must have matched the whole pattern.
   // We do not need (can not do) any more checks on the value of 'matches' here