正则表达式在 Swift 中的一对方括号之间获取文本

Regex to get text between pair of square brackets in Swift

<strong>Lorem Ipsum.<\/strong> Lorem Ipsum. [link-to:shop-page \"instore-pickup\"]Learn More[\/link-to]

给定上面的示例字符串(它包括 HTML),我从第 3 方服务获得它并且我无法控制改进或规范化它以适应 HTML 标准.

我需要以某种方式解析这部分 [link-to:shop-page \"instore-pickup\"]Learn More[\/link-to] 以获得 Learn More 值。

我试过 \[.*?\](.*?)\[.*?\] 正则表达式,但它不能满足我的需要。 结果得到 [link-to:shop-page \"instore-pickup\"]Learn More[/link-to]

func matches(for 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: [=11=].range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Wiktor,感谢您指出这一点,工作片段:

func matches(for 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: [=10=].range(at: 1))}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

[=11=].range(at: 1) 给出第 1 组。