Skip to content

Instantly share code, notes, and snippets.

Embed
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 a pair of square brackets in the end of the sentence.
func grabCity(_ str: String) -> String {
// the commented line below (the regex to be exact) gets just the last word! which is wrong, my fault though, i didn't read the challenge corectly!
// let regex = try! NSRegularExpression(pattern: "(\\w+)(?!.*\\w)", options: [])
// the regex below get every matches in the sentence that is being wrapped in a pair of square brackets.
let regex = try! NSRegularExpression(pattern: "(?<=\\[)(.+?)(?=\\])", options: [])
// the "result" below is of type NSTextCheckingResult which is an array, since the challenge askes for the last match, and i couldn't get the last match through the regex, i ened up gtting the last match via the "last" item in the array.
let result = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.count)).last
/*
// from line 11 to 18, is an alternative for getting the matches out of the result array, since it is an array (of type NSTextCheckingResult) you can iterate thtough it (loop though it)
// you can use each one of these solutions!
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])
}
}
*/
// here, in the line below, you get the desired matches out of the "result" array. this works in all versions of Swift, from 3 to the recent one.
return result.map{ String(str[str.index(str.startIndex, offsetBy: $0.range.location)..<str.index(str.startIndex, offsetBy: $0.range.location+$0.range.length)]) }!
// the line below also gives you the desired matches bu it works just in swift 5
// return result.map{ String(str[Range($0.range, in: str)!]) }.joined()
}
// nothing fancy here! just a print statement! i usually like to know the address of my print statement when i see it in the consol :) it prints the line number and the file name and the result of the print statement!
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]"))
// if you know how to get the last match via regex, please please please let me know :)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.