Created
August 2, 2016 09:30
-
-
Save nsomar/bb8f5ea253a4f9b8c3128238ea658ed8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func cleanRegex(pattern: String) -> String { | |
let res = pattern.characters.enumerate().reduce(([], [])) { (acc, enumerator) -> ([Int], [Int]) in | |
if enumerator.element == "{" { | |
return (acc.0 + [enumerator.index], acc.1) | |
} | |
if enumerator.element == "}" { | |
if let lastOpen = acc.0.last { | |
let range = NSRange(location: lastOpen, length: enumerator.index - lastOpen + 1) | |
if isQuantifier(pattern, range: range) { | |
return (Array(acc.0.dropLast()), acc.1) | |
} else { | |
return (acc.0, acc.1 + [enumerator.index]) | |
} | |
} else { | |
return (acc.0, acc.1 + [enumerator.index]) | |
} | |
} | |
return acc | |
} | |
let allBrackets = res.0 + res.1 | |
let characters = | |
pattern.characters.enumerate().reduce([Character]()) { (acc, enumerator) -> [Character] in | |
if allBrackets.contains(enumerator.index) { | |
return acc + ["\\", enumerator.element] | |
} | |
return acc + [enumerator.element] | |
} | |
return String.init(characters) | |
} | |
func isQuantifier(pattern: String, range: NSRange) -> Bool { | |
guard | |
let reg = try? NSRegularExpression.init(pattern: "\\{\\d{1,},?\\d*\\}", | |
options: .DotMatchesLineSeparators) else { | |
return false | |
} | |
return reg.firstMatchInString(pattern, options: .Anchored, range: range) != nil | |
} | |
let pattern = "{This is Kinda {1}Cool. It might {{}} ge{t} kinda }}{{{complicated}}" | |
print(cleanRegex(pattern)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment