Reputation: 41
I need to extract the numbers from a string ex. "(1,1)(3,3)(4,4)". I tried with "\d(,)\d)", but I get the comma too. How can I exclude the comma and make e tuple or an array of arrays [[1,1],[3,3]...
let str = "(1,1) (2,2) (3,3)"
let pattern = "\\d(,)\\d"
let regex = try! NSRegularExpression(pattern:pattern)
let results = regex.matches(in: str, options: [], range: range)
Upvotes: 3
Views: 324
Reputation: 626738
You can use
let s = "(1,1) (2,2) (3,3)"
print(s.replacingOccurrences(of: #"\)\s*\("#, with: "|", options: .regularExpression)
.trimmingCharacters(in: ["(", ")"])
.components(separatedBy: "|")
.map { $0.components(separatedBy: [",", "."]).map { Int($0)!} }
)
Output: [[1, 1], [2, 2], [3, 3]]
.
This will work even if you have a single number inside parentheses. If you have let s = "(1,1) (3,3)(4.4)(4)"
, the output will be [[1, 1], [3, 3], [4, 4], [4]]
.
Details
\)\s*\(
matches )
, 0+ whitespace chars, (
, .replacingOccurrences(of: #"\)\s*\("#, with: "|", options: .regularExpression)
replaces all these matches with |
.trimmingCharacters(in: ["(", ")"])
removes (
and )
at the start/end of the string.components(separatedBy: "|")
splits the resulting string with |
.map { $0.components(separatedBy: [",", "."]).map { Int($0)!} }
splits each tuple into constituent numbers and then casts to Int.Upvotes: 1
Reputation: 285069
A possible solution is to capture only the digits, replace each occurrence with "[$1,$2]"
, then insert commas between, wrap the expression in square brackets to get JSON and decode it
let str = "(1,1)(3,3)(4.4)"
let str1 = str.replacingOccurrences(of: "\\((\\d+)[.,](\\d+)\\)", with: "[$1,$2]", options: .regularExpression).replacingOccurrences(of: "][", with: "],[")
let result = try! JSONDecoder().decode([[Int]].self, from: Data(("[" + str1 + "]").utf8))
The intermediate results are:
"[1,1][3,3][4,4]"
"[1,1],[3,3],[4,4]"
"[[1,1],[3,3],[4,4]]"
Upvotes: 2