             var regexMatches = [regmatch_t](count: maxMatches, repeatedValue: regmatch_t())
             let result = regexec(&preg, string, regexMatches.count, &regexMatches, options.rawValue)
 
-            if result == 1 {
+            if result == REG_NOMATCH {
                 break
             }
 
             for var j = 1; regexMatches[j].rm_so != -1; j++ {
                 let start = Int(regexMatches[j].rm_so)
                 let end = Int(regexMatches[j].rm_eo)
-                let match = string[string.startIndex.advancedBy(start) ..<  string.startIndex.advancedBy(end)]
-                groups.append(match)
+                if let match = String(string.utf8[string.utf8.startIndex.advancedBy(start) ..< string.utf8.startIndex.advancedBy(end)]) {
+                    groups.append(match)
+                }
             }
 
             let offset = Int(regexMatches[0].rm_eo)
-            string = string[string.startIndex.advancedBy(offset) ..< string.endIndex]
+            if let offsetString = String(string.utf8[string.utf8.startIndex.advancedBy(offset) ..< string.utf8.endIndex]) {
+                string = offsetString
+            } else {
+                break
+            }
         }
 
         return groups
     }
 
-    public func replace(string: String, withTemplate template: String, options: MatchOptions = []) -> String {
-        var string = string
+    public func replace(var string: String, withTemplate template: String, options: MatchOptions = []) -> String {
         let maxMatches = 10
         var totalReplacedString: String = ""
 

            self.rawValue = rawValue
        }

        public static let Basic =            RegexOptions(rawValue: 0)
        public static let Extended =         RegexOptions(rawValue: 1)
        public static let CaseInsensitive =  RegexOptions(rawValue: 2)
        public static let ResultOnly =       RegexOptions(rawValue: 8)
        public static let NewLineSensitive = RegexOptions(rawValue: 4)
    }

    public struct MatchOptions: OptionSetType {

        var regexMatches = [regmatch_t](count: 1, repeatedValue: regmatch_t())
        let result = regexec(&preg, string, regexMatches.count, &regexMatches, options.rawValue)

        if result == REG_NOMATCH {
            return false
        }

        return true
    }

    public func groups(var string: String, options: MatchOptions = []) -> [String] {
        let maxMatches = 10
        var groups = [String]()

