I'm obtaining a response to an HTTP POST request with the code
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {data, response, error in
if error != nil {
println("error=\(error)")
return
}
// Get the response to the HTTP POST
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)!}
task.resume()
I tried to define two regular expressions
let regex0: NSRegularExpression = NSRegularExpression(pattern: "<b>District Representatives:</b>", options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)!
let regex1: NSRegularExpression = NSRegularExpression(pattern: "\\A.*<b>District Representatives:</b>.*href=\"http://www\.sec\.state\.ma\.us/ele/eledist/con11idx\.htm#D[1-9]\" target=\"_blank\">(.*?)</a>.*href=\"http://www\.sec\.state\.ma\.us/ele/eledist/sen11idx\.htm#[0-9]{0,5}[a-z]{1,20}\" target=\"_blank\">(.*?)</a>.*\"http://www\.sec\.state\.ma\.us/ele/eledist/reps11idx\.htm#[a-z]{1,13}[0-9]{0,2}\" target=\"_blank\">(.*?)</a>.*\\z", options: NSRegularExpressionOptions.DotMatchesLineSeparators, error: nil)!
But Xcode gives me the error message "Expected expression" on the definition of regex1.
I want to test whether responseString is matched by regex0. I tried using
var numberOfMatches: Int = regex0.numberOfMatchesInString(responseString, options:nil, range: (NSMakeRange(0, responseString.length)))
but I got the error message "Use of unresolved identifier responseString"
I'd like to know how to test for the success of a regular expression match. In this case, I could just test whether responseString contains my test string. That seems to work nicely with Swift Strings, but I can't get it to work with an NSString.
I think the pattern in my regex1 regular expression is OK, because I tested the equivalent pattern in TextWrangler. The pattern I used there was
(?s)\A.*<b>District Representatives:</b>.*href="http://www\.sec\.state\.ma\.us/ele/eledist/con11idx\.htm#D[1-9]" target="_blank">(.*?)</a>.*href="http://www\.sec\.state\.ma\.us/ele/eledist/sen11idx\.htm#[0-9]{0,5}[a-z]{1,20}" target="_blank">(.*?)</a>.*"http://www\.sec\.state\.ma\.us/ele/eledist/reps11idx\.htm#[a-z]{1,13}[0-9]{0,2}" target="_blank">(.*?)</a>.*\z
The only (intentional) differences are that in the Swift literal, all the Double-Quotes and Backslashes had to be escaped with a backslash and the TextWrangler pattern starts with (?s) which is the equivalent of NSRegularExpressionOptions.DotMatchesLineSeparators.
I wanted to use regex1 to modify responseString as follows
responseString.replaceMatchesInString(options: nil, range: NSMakeRange(0, responseString.length), withTemplate template: "$1\t$2\t$3")
But that didn't work either.
I naively thought that since I've been using regular expressions for 30 years, that part would be easy. Apparently not.