Evgeny Karkan
Evgeny Karkan

Reputation: 9612

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]

Given a sample string above (it includes HTML) which I'm getting from 3-rd party service and it's out of my control to improve or normalize it to fit the HTML standard.

I need to parse this part somehow [link-to:shop-page \"instore-pickup\"]Learn More[\/link-to] to get the Learn More value.

I've tried \\[.*?\\](.*?)\\[.*?\\] regex, but it doesn't work for my need. Getting [link-to:shop-page \"instore-pickup\"]Learn More[/link-to] as a result.

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 []
    }
}

Upvotes: 2

Views: 1130

Answers (1)

Evgeny Karkan
Evgeny Karkan

Reputation: 9612

Wiktor, thanks for pointing on that, working snippet:

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) gives Group 1.

Upvotes: 2

Related Questions