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

时间:2019-10-30 23:05:39

标签: ios swift regex nsregularexpression

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

给出上面的示例字符串(包括HTML),该字符串是我从第三方服务获得的,因此无法改善或标准化它以适合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: $0.range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

1 个答案:

答案 0 :(得分:0)

维克多(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: $0.range(at: 1))}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

$0.range(at: 1)分配组1。