Reputation: 11
In Swift I have a string like:
let str = "5~895893799,,6~898593679,,7~895893679,,8~895893799,,5~895893799,,6~898593679,,7~895893679,,8~895893799";
From this I need to get only the number which is before "~" which is [5,6,7,8,5,6,7,8]
How can I achieve this?
Upvotes: 0
Views: 45
Reputation: 18581
You could define this regular expression:
let regex = try! NSRegularExpression(pattern: #"\d+(?=~)"#)
\d
: matches any digit+
: this is the one or more quantifier(?=~)
: Positive lookahead for "~"and use it like so:
let range = NSRange(location: 0, length: (str as NSString).length)
let matches = regex.matches(in: str, range: range)
let strings: [String] = matches.map { match in
let subRange = match.range
let startIndex = str.index(str.startIndex, offsetBy: subRange.lowerBound)
let endIndex = str.index(str.startIndex, offsetBy: subRange.upperBound)
let subString = String(str[startIndex..<endIndex])
return subString
}
let numbers = strings.compactMap(Int.init) //[5, 6, 7, 8, 5, 6, 7, 8]
Upvotes: 0
Reputation: 318794
Make use of components(separatedBy:)
and compactMap
.
let str = "5~895893799,,6~898593679,,7~895893679,,8~895893799,,5~895893799,,6~898593679,,7~895893679,,8~895893799"
let nums = str.components(separatedBy: ",,")
.compactMap { $0.components(separatedBy: "~").first }
That gives the string array:
["5", "6", "7", "8", "5", "6", "7", "8"]
If you want an array of Int, add:
.compactMap { Int($0) }
to the end.
let nums = str.components(separatedBy: ",,")
.compactMap { $0.components(separatedBy: "~").first }
.compactMap { Int($0) }
That gives:
[5, 6, 7, 8, 5, 6, 7, 8]
Upvotes: 3