diff --git a/Sources/Lingo/StringInterpolator.swift b/Sources/Lingo/StringInterpolator.swift index f6a8dcb..8e61c48 100644 --- a/Sources/Lingo/StringInterpolator.swift +++ b/Sources/Lingo/StringInterpolator.swift @@ -2,21 +2,18 @@ import Foundation final class StringInterpolator { - private static let regularExpression = try! NSRegularExpression(pattern: "\\%\\{[^\\}]*\\}", options: []) // swiftlint:disable:this force_try - + private static let regexPattern = "\\%\\{[^\\}]*\\}" + /// Input string is in format: "You have %{count} unread messages". /// The function finds all placeholders and replaces them with a value specified in interpolations dictionary func interpolate(_ rawString: String, with interpolations: [String: Any]) -> String { - var result = rawString - let matches = StringInterpolator.regularExpression.matches(in: rawString, options: [], range: NSRange.init(location: 0, length: rawString.count)) - for match in matches { - let range: NSRange = match.range + let ranges: [Range] = findRanges(in: rawString, startingFrom: rawString.startIndex) + + return ranges.reduce(into: rawString) { result, range in // Extract whole capture group string. Will contain string like: "%{count}" - let startIndex = rawString.index(rawString.startIndex, offsetBy: range.location) - let endIndex = rawString.index(startIndex, offsetBy: range.length) - let matchedString = String(rawString[startIndex.. [Range] { + let end = text.endIndex + guard let range = text.range(of: Self.regexPattern, options: .regularExpression, + range: start..