     var tokens: [Token] = []
 
     let scanner = Scanner(templateString)
-
-    let map = [
-      "{{": "}}",
-      "{%": "%}",
-      "{#": "#}",
-      ]
-
     while !scanner.isEmpty {
-      if let text = scanner.scan(until: ["{{", "{%", "{#"]) {
-        if !text.1.isEmpty {
-          tokens.append(createToken(string: text.1, at: scanner.range))
+      if let (char, text) = scanner.scanForTokenStart(Lexer.tokenChars) {
+        if !text.isEmpty {
+          tokens.append(createToken(string: text, at: scanner.range))
         }
 
-        let end = map[text.0]!
-        let result = scanner.scan(until: end, returnUntil: true)
+        guard let end = Lexer.tokenCharMap[char] else { continue }
+        let result = scanner.scanForTokenEnd(end)
         tokens.append(createToken(string: result, at: scanner.range))
       } else {
         tokens.append(createToken(string: scanner.content, at: scanner.range))

    return content.isEmpty
  }

  func scan(until: String, returnUntil: Bool = false) -> String {
    var index = content.startIndex

    if until.isEmpty {
      return ""
    }

    range = range.upperBound..<range.upperBound
    while index != content.endIndex {
      let substring = String(content[index...])

      if substring.hasPrefix(until) {
        let result = String(content[..<index])

        if returnUntil {
          range = range.lowerBound..<originalContent.index(range.upperBound, offsetBy: until.count)
          content = String(substring[until.endIndex...])
          return result + until
        }

        content = substring
        return result
      }

      index = content.index(after: index)
      range = range.lowerBound..<originalContent.index(after: range.upperBound)
    }

    content = ""
    return ""
  }

  func scan(until: [String]) -> (String, String)? {
    if until.isEmpty {
      return nil
    }

    var index = content.startIndex
    range = range.upperBound..<range.upperBound
    while index != content.endIndex {
      let substring = String(content[index...])
      for string in until {
        if substring.hasPrefix(string) {
          let result = String(content[..<index])
          content = substring
          return (string, result)
        }
      }

      index = content.index(after: index)
      range = range.lowerBound..<originalContent.index(after: range.upperBound)
    }

    return nil
  }
}


extension String {
  func findFirstNot(character: Character) -> String.Index? {

  let templateName: String?
  let templateString: String
  let lines: [Line]

  private static let tokenChars: [Unicode.Scalar] = ["{", "%", "#"]
  private static let tokenCharMap: [Unicode.Scalar: Unicode.Scalar] = [
    "{": "}",
    "%": "%",
    "#": "#"
  ]

  init(templateName: String? = nil, templateString: String) {
    self.templateName = templateName
