             // Get the capture groups
             for matchRangeIdx in 0..<matchResult.numberOfRanges {
                 let matchRange = matchResult.rangeAtIndex(matchRangeIdx)
-                let beginIndex = advance(subject.startIndex, matchRange.location)
-                let endIndex = advance(beginIndex, matchRange.length)
-
-                ranges.append(beginIndex..<endIndex)
+
+                if matchRange.location == NSNotFound {
+                    ranges.append(nil)
+                } else {
+                    let beginIndex = advance(subject.startIndex, matchRange.location)
+                    let endIndex = advance(beginIndex, matchRange.length)
+
+                    ranges.append(beginIndex..<endIndex)
+                }
             }
 
             self.ranges = ranges

            var pos: String.Index = str.startIndex

            for match in matches {
                let range = match.ranges[0]

                buffer += str[pos..<range.startIndex]
                buffer += "\\"
                buffer += str[range]

                pos = range.endIndex
            }

            buffer += str[pos..<str.endIndex]


            :returns: Subscript for the capture group.
        */
        public subscript(index: Int) -> String? {
            if let range = ranges[index] {
                return subject[range]
            } else {
                return nil
            }
        }
    }

