firstMatchInString

/ 
import UIKit
import Foundation
/
var arr = ["Zero","One","Two0,", "3", "Four)-", "Fi-ve"]
/
let regex = NSRegularExpression(pattern: ".*([^A-Za-z0-9]).*", options: nil, error: nil)!
/
for var i = 0; i < arr.count; i++ {
    var regResult = regex.firstMatchInString(arr[i], options: nil, range: NSMakeRange(0, count(arr[i])))
   
    if regResult != nil {
       
        /
        var loc = regResult!.rangeAtIndex(1) // returns (4,1)(5,1)(2,1)
     }


The second value for regResult!.rangeAtIndex(1) should be (4,1) not (5,1). For some reason firstMatchInString is returning the last match in the string and not the first. Is this broken or am I missing something?

It has to do with your regex pattern and the use of .* which will try to match as many characters as possible, so the first match it finds is the one where the first .* is matching the most characters possible.


"[A-Za-z0-9]*([^A-Za-z0-9])[A-Za-z0-9]*" would work, but I'm sure someone who knows more about regex could give you a more efficient pattern.

firstMatchInString
 
 
Q