[libc++] Fixes backreferences for extended grammar.

The regex backreferences were not properly parsed and used when using
the extended grammar. This change parses them. The issue was found while
working on PR34297.

Thanks to Mark de Wever for the patch!

Differential Revision: https://reviews.llvm.org/D62451

Cr-Mirrored-From: https://chromium.googlesource.com/external/github.com/llvm/llvm-project
Cr-Mirrored-Commit: 6ba2d7b166c2e07dfc8328a8253276710619b1fe
diff --git a/include/regex b/include/regex
index 5ac9e32..e349fa6 100644
--- a/include/regex
+++ b/include/regex
@@ -2837,6 +2837,8 @@
         __parse_awk_escape(_ForwardIterator __first, _ForwardIterator __last,
                           basic_string<_CharT>* __str = nullptr);
 
+    bool __test_back_ref(_CharT c);
+
     _LIBCPP_INLINE_VISIBILITY
     void __push_l_anchor();
     void __push_r_anchor();
@@ -3408,18 +3410,8 @@
     if (__first != __last)
     {
         _ForwardIterator __temp = _VSTD::next(__first);
-        if (__temp != __last)
-        {
-            if (*__first == '\\')
-            {
-                int __val = __traits_.value(*__temp, 10);
-                if (__val >= 1 && __val <= 9)
-                {
-                    __push_back_ref(__val);
-                    __first = ++__temp;
-                }
-            }
-        }
+        if (__temp != __last && *__first == '\\' && __test_back_ref(*__temp))
+            __first = ++__temp;
     }
     return __first;
 }
@@ -3547,6 +3539,8 @@
                 default:
                     if (__get_grammar(__flags_) == awk)
                         __first = __parse_awk_escape(++__first, __last);
+                    else if(__test_back_ref(*__temp))
+                        __first = ++__temp;
                     break;
                 }
             }
@@ -4661,6 +4655,20 @@
 }
 
 template <class _CharT, class _Traits>
+bool
+basic_regex<_CharT, _Traits>::__test_back_ref(_CharT c)
+{
+    unsigned __val = __traits_.value(c, 10);
+    if (__val >= 1 && __val <= 9)
+    {
+        __push_back_ref(__val);
+        return true;
+    }
+
+    return false;
+}
+
+template <class _CharT, class _Traits>
 void
 basic_regex<_CharT, _Traits>::__push_loop(size_t __min, size_t __max,
         __owns_one_state<_CharT>* __s, size_t __mexp_begin, size_t __mexp_end,