Swift正则提取:从括号字符串提取数字生成二维数组
Fixing Your Regex to Extract a 2D Array of Numbers
Hey there! I see you're trying to pull number pairs from a string like "(1,1)(3,3)(4,4)" and turn them into a 2D array, but your current regex is including commas and not capturing the full pairs correctly. Let's fix that step by step.
What's Wrong with the Original Regex?
Your pattern \d(,)\d only matches single digits around a comma, and it captures the comma as part of the match. It also doesn't account for multi-digit numbers (like (10,20)) or properly isolate each pair inside parentheses.
The Corrected Regex
We need a pattern that targets each parenthesized pair and captures the two numbers separately:
\((\d+),(\d+)\)
Let's break this down:
\(: Escapes the left parenthesis (since parentheses are special regex characters)(\d+): First capture group, matches one or more digits (supports multi-digit numbers),: Matches the comma separating the numbers(\d+): Second capture group, matches the second number\): Escapes the right parenthesis
Updated Swift Code
Here's how to implement this to build your 2D array:
let str = "(1,1) (2,2) (3,3)" let pattern = "\\((\\d+),(\\d+)\\)" // Double backslashes for Swift string escaping let regex = try! NSRegularExpression(pattern: pattern) let range = NSRange(str.startIndex..., in: str) var numberPairs: [[Int]] = [] // Iterate through all matches and extract the captured numbers regex.enumerateMatches(in: str, options: [], range: range) { match, _, _ in guard let match = match else { return } // Extract first number from capture group 1 if let num1Range = Range(match.range(at: 1), in: str), let num1 = Int(str[num1Range]) { // Extract second number from capture group 2 if let num2Range = Range(match.range(at: 2), in: str), let num2 = Int(str[num2Range]) { numberPairs.append([num1, num2]) } } } print(numberPairs) // Output: [[1, 1], [2, 2], [3, 3]]
Key Improvements
- Supports multi-digit numbers: Works with pairs like
(123,456)instead of just single digits - Captures pure numbers: No more dealing with commas—we directly grab the digits from the capture groups
- Handles any spacing: Works whether pairs are separated by spaces (like your example) or not (e.g.,
"(1,1)(3,3)(4,4)")
内容的提问来源于stack exchange,提问作者John Aron




