2

When I run the following code in a Playground, I get an invalid range as a result:

import Cocoa

var error: NSError?
var captureGroups: [String] = []
var input = "http://www.google.com"

var pattern = "(https?|ftp|file|gopher|mailto|news|nntp|telnet|wais)://[a-zA-Z0-9_@]+([.:][a-zA-Z0-9_@]+)*/?[a-zA-Z0-9_?,%#~&/\\-]+([:.][a-zA-Z0-9_?,%#~&/\\-]+)*"

var internalExpression = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &error)!

if let match = internalExpression.firstMatchInString(input, options: nil, range: NSMakeRange(0, count(input))) {

    match.numberOfRanges // 4
    match.rangeAtIndex(0) // (0, 21)
    match.rangeAtIndex(1) // (0, 4)
    match.rangeAtIndex(2) // (17, 3)
    match.rangeAtIndex(3) // (9223372036854775807,0)
}

This code has worked for other regular expressions, it seems to be only this one that is giving it trouble. I am not a RegEx expert, so I am unsure as to how I should proceed.

2 Answers2

1

You do an if test like this:

if match.rangeAtIndex(3).location != NSNotFound {
    // Do if found result.
} else {
    // Handle error.
}
Cai
  • 3,609
  • 2
  • 19
  • 39
0

if you want to parse a URL, it's probably easiest to use NSURL:

if let url = NSURL(string: input) {
    println(url.scheme)
    println(url.host)
    println(url.path)
    println(url.pathComponents)
    println(url.query)
}

If you want help fixing the regex and understanding why you received NSNotFound, you should clearly describe what you were hoping to parse out of it. But when dealing with URLs, NSURL is easiest.

Rob
  • 415,655
  • 72
  • 787
  • 1,044