eharo2
eharo2

Reputation: 2642

RegularExpression matchesInString issue in Swift

I am converting a CoreText based app to Swift and I am facing an issue when getting the matches to a regular expression in the text.

This is the sample code

let regexOptions = NSRegularExpressionOptions.CaseInsensitive | NSRegularExpressionOptions.DotMatchesLineSeparators
let regex = NSRegularExpression.regularExpressionWithPattern("(.*?)(<[^>]+>|\\Z)", options: regexOptions, error: nil)
var results: Array<NSTextCheckingResult> = regex.matchesInString(text, options: 0, range: NSMakeRange(0, countElements(text)))

According to the documentation, the matchesInString function returns an array of NSTextCheckingResults, but the compiler complains stating that "The Expression of type anyObject[] can´t be converted to "NSMatchingOptions". Any idea of what might be wrong here?

Upvotes: 4

Views: 4075

Answers (2)

clearfix
clearfix

Reputation: 467

I just sat with a problem related to some regexes and thought I would add a warning to the answer submitted above. My regexes matches seemed to be cut short and it turned out that the range i supplied was incorrect. I generated the range in the way described by @fqdn. It turned out that my strings contained carriage returns (\u{A}) and that these were not counted by the countElements function. I countered this by calling .unicodeScalars on the string which seems to correctify the lenght.

println(countElements("\u{A}\u{A}\u{A}\n\u{D}\n\u{D}\n\u{D}\n\u{D}\n")) //8
println(countElements("\u{A}\u{A}\u{A}\n\u{D}\n\u{D}\n\u{D}\n\u{D}\n".unicodeScalars))  //12

Disclaimer: This is quite probably a swift-bug and might get fixed in a later version.

Upvotes: 0

fqdn
fqdn

Reputation: 2843

Try assigning to your results variable like this:

var results = regex.matchesInString(text, options: nil, range: NSMakeRange(0, countElements(text))) as Array<NSTextCheckingResult>

  1. the return type is Array<AnyObject>[]!, you can cast here (as in the above example) or later when you check the members of the collection

  2. in Swift options take nil to represent an empty option set (vs. 0 in Objective-C)

Upvotes: 7

Related Questions