Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
"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{ String(str[str.index(str.startIndex, offsetBy: $0.range.location)..<str.index(str.startIndex, offsetBy: $0.range.location+$0.range.length)]) }!
// return{ 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