Created
January 8, 2020 10:10
-
-
Save alekseypotapov-dev/5119ea896454fe8fe40f59436ad1b04c to your computer and use it in GitHub Desktop.
Just to remember
This file contains hidden or 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 UIKit | |
// [^] Negated set - Match any character that is not in the set. | |
// @ Character - Matches "@" character (char code 64). | |
// * Quantifier - Match 0 or more of pending token. | |
// $ End - Matches the end of the string, or the end of a line if the multiline flag (m) is enabled. This matches a position, not a character. | |
func matchesRegex(_ regex: String, in text: String) -> String { | |
do { | |
let regex = try NSRegularExpression(pattern: regex) | |
let nsString = text as NSString | |
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length)) | |
return results.map { nsString.substring(with: $0.range)}.first ?? "" | |
} catch let error { | |
print("invalid regex: \(error.localizedDescription)") | |
return "" | |
} | |
} | |
let arr = ["004-STO05-Nature.mp4 @ 04 Nature", "003-STO05-Pictogram.mp4 @ 03 Pictogram", "007-STO05-Retail.jpg @ 07 Retail", "001-STO05-CHEMICAL.mp4 @ 01 Chemical", "006-STO05-Transportation.jpg @ 06 Transportation", "002-STO05-SQUARECITY.mp4 @ 02 Square City", "008-STO05-SPATIAL.mp4 @ 08 Spatial", "005-STO05-CityScape.jpg @ 05 CityScape"] | |
var dict = [String: String]() | |
for str in arr { | |
let matched = matchesRegex("[^@]*$", in: str) | |
if !matched.isEmpty { | |
dict[str] = matched.trimmingCharacters(in: .whitespaces) | |
} | |
} | |
let sorted = dict.sorted{ $0.value > $1.value }.map{ $0.key } | |
print(sorted) | |
// OR | |
let sortedInline = arr.sorted(by: { $0.components(separatedBy: "@").last ?? "" > $1.components(separatedBy: "@").last ?? "" }) | |
print(sortedInline) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment