Search code examples
htmliosregexswiftnsregularexpression

NSRegularExpression Check Content of HTML String


I get html string from server. If it's empty, we don't do anything. Otherwise, we show them on UIWebView. I can easily check with .isEmpty in a simple if statement.

    Services.getBusinessProfile(countryCode: countryCode, companyId: companyData.cId) { (req, html) in

            if !html.isEmpty {
// rest of the code

Problem is, sometimes I get empty tag:

<span style=\"font-family:HelveticaNeue; font-size: 16\"></span>

How can I check the content of this tag? I think I have to use NSRegularExpression for this, as this thread: NSRegularExpression to extract text between two XML tags. But I have no clue how to use it.


Solution

  • If you just need to retrieve the substring between the first span tag in your html text you can do it using range of string upperBound and lowerBound to get your substring as follow:

    let htmlString = "<span style=\"font-family:HelveticaNeue; font-size: 16\">Indonesia</span>"
    
    if let lower = htmlString.range(of: "<span style=\"font-family:HelveticaNeue; font-size: 16\">")?.upperBound,
        let upper = htmlString.range(of: "</span>", range: lower..<htmlString.endIndex)?.lowerBound {
        let text = htmlString[lower..<upper]   //  "Indonesia"
    }