Skip to content

Instantly share code, notes, and snippets.

@TheAlienMann
Created September 16, 2019 09:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheAlienMann/4686f25ebf21cadaac965d1a025c9d3d to your computer and use it in GitHub Desktop.
Save TheAlienMann/4686f25ebf21cadaac965d1a025c9d3d to your computer and use it in GitHub Desktop.
"Grab The City" is a challenge that wants you to extract the name of the city in a given sentence which the name is wrapped in pair of square bracket
func grabCity(_ str: String) -> String {
// let regex = try! NSRegularExpression(pattern: "(\\w+)(?!.*\\w)", options: [])
let regex = try! NSRegularExpression(pattern: "(?<=\\[)(.+?)(?=\\])", options: [])
let result = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.count)).last
/*
for match in result {
for n in 0..<match.numberOfRanges {
let range = match.range(at: n)
let r = str.index(str.startIndex, offsetBy: range.location)..<str.index(str.startIndex, offsetBy: range.location+range.length)
// print(#line, #file.components(separatedBy: "/").last!, str.substring(with: r))
print(#line, #file.components(separatedBy: "/").last!, str[r])
}
}
*/
return result.map{ String(str[str.index(str.startIndex, offsetBy: $0.range.location)..<str.index(str.startIndex, offsetBy: $0.range.location+$0.range.length)]) }!
// return result.map{ String(str[Range($0.range, in: str)!]) }.joined()
}
print(#line, #file.components(separatedBy: "/").last!, grabCity("[Last Day!] Beer Festival [Munich]"))
print(#line, #file.components(separatedBy: "/").last!, grabCity("[50% Off!][Group Tours Included] 5-Day Trip to Onsen [Kyoto]"))
print(#line, #file.components(separatedBy: "/").last!, grabCity("[Duration: 7 hours] Tour of the Maritimes [Prince Edward Island]"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment