我正在使用代码获取对 HTTP POST 请求的响应
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()
我尝试定义两个正则表达式
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)!
但是 Xcode 在 regex1 的定义上给我错误信息“Expected expression”。
我想测试 responseString 是否与 regex0 匹配。我尝试使用
var numberOfMatches: Int = regex0.numberOfMatchesInString(responseString, options:nil, range: (NSMakeRange(0, responseString.length)))
但我收到错误消息“使用未解析的标识符 responseString”
我想知道如何测试正则表达式匹配是否成功。在这种情况下,我可以只测试 responseString 是否包含我的测试字符串。这似乎与 Swift 字符串一起工作得很好,但我无法让它与 NSString 一起工作。
我认为我的 regex1 正则表达式中的模式没问题,因为我在 TextWrangler 中测试了等效模式。我在那里使用的模式是
(?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
唯一(有意)的区别是在 Swift 文字中,所有双引号和反斜杠都必须使用反斜杠进行转义,而 TextWrangler 模式以 (?s) 开头,这相当于 NSRegularExpressionOptions.DotMatchesLineSeparators。
我想用regex1修改responseString如下
responseString.replaceMatchesInString(options: nil, range: NSMakeRange(0, responseString.length), withTemplate template: "$1\t$2\t$3")
但这也没有用。
我天真地认为,既然我已经使用正则表达式 30 年了,那部分会很容易。显然不是。
最佳答案
您的 regex1
缺少文字点上的双转义符(参见 www\.sec\.state\.ma\.us
)。
正确的 regex1 声明将是
@"\\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"
您 Use of unresolved identifier responseString 可能是因为您在声明和使用 numberOfMatches
的方法之外声明了 responseString
。
关于regex - 在 Swift 中使用模板的 NSRegularExpression,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30520984/