0

I'm accessing the HTML of a webpage after the user has submitted information.

If I have...

var htmlString = "This is the massive HTML string - it has lots of characters "FindStringDetails"<123789456.123456>  This is a massive HTML string - "
var findString = "FindStringDetails\"<"

Is there a suitable way that I could extract the numbers that come after "FindStringDetails"< to give me 123789456.123456 ?

M.Strachan
  • 125
  • 2
  • 11

1 Answers1

0
import Foundation

var htmlString = "This is the massive HTML string - it has lots of characters \"FindStringDetails\"<123789456.123456>  This is a massive HTML string - "
var findString = "FindStringDetails\"<"

extension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = NSString(string: self)
        let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map { result.range(at: $0).location != NSNotFound
                ? nsString.substring(with: result.range(at: $0))
                : ""
            }
        }
    }
}

let m = htmlString.matchingStrings(regex: "\(findString)(\\d+)\\.(\\d+)")

print(m[0][1]) // 123789456
print(m[0][2]) // 123456

(Code adapted from here.)

Community
  • 1
  • 1
emlai
  • 37,861
  • 9
  • 87
  • 140
  • Thanks for your response. This has given me a lot to look at. If the query that I was trying to get contained numbers and digits and also included a space. "John3 321" What could I do to get this as one string? – M.Strachan Apr 23 '17 at 19:01
  • tuple_cat has answered your original question. You should accept the answer to your question and ask a new one. – Mozahler Apr 23 '17 at 19:04
  • You mean like `"\(findString)(\\d+) (\\d+)"`? (Or `"\(findString)(\\d+)[\\. ](\\d+)"` to match both.) – emlai Apr 23 '17 at 19:09