3

I tried to translate a PHP function to Swift. The function is used to format a String to an other according the my regular expression. So here's what I do in PHP :

    preg_match('/P(([0-9]+)Y)?(([0-9]+)M)?(([0-9]+)D)?T?(([0-9]+)H)?(([0-9]+)M)?(([0-9]+)(\.[0-9]+)?S)?/', $duration, $matches)

I use the $matches array to format my new String. So, in Swift, i found this thread : Swift extract regex matches, which seems to do what I want. But when i get the result, my array is only one String long, with my entire input...

    func matchesForRegexInText(regex: String!, text: String!) -> [String] {

       let regex = NSRegularExpression(pattern: regex,
           options: nil, error: nil)!
       let nsString = text as NSString
       let results = regex.matchesInString(text,
       options: nil, range: NSMakeRange(0, nsString.length)) as    [NSTextCheckingResult]
       return map(results) { nsString.substringWithRange($0.range)}
    }

    let matches = matchesForRegexInText("P(([0-9]+)Y)?(([0-9]+)M)?(([0-9]+)D)?T?(([0-9]+)H)?(([0-9]+)M)?(([0-9]+)(.[0-9]+)?S)?", text: "PT00042H42M42S")
    println(matches)
    // [PT00042H42M42S]

Do you know what's wrong?

Thank you for your answers!

Community
  • 1
  • 1
tmato
  • 71
  • 8

1 Answers1

1

The array contains one element because the input contains exactly one string "PT00042H42M42S" which matches the pattern.

If you want to retrieve the matching capture groups then you have to use rangeAtIndex: on the NSTextCheckingResult. Example:

let pattern = "P(([0-9]+)Y)?(([0-9]+)M)?(([0-9]+)D)?T?(([0-9]+)H)?(([0-9]+)M)?(([0-9]+)(.[0-9]+)?S)?"
let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil)!
let text = "PT00042H42M42S"
let nsString = text as NSString
if let result = regex.firstMatchInString(text, options: nil, range: NSMakeRange(0, nsString.length)) {
    for i in 0 ..< result.numberOfRanges {
        let range = result.rangeAtIndex(i)
        if range.location != NSNotFound {
            let substring = nsString.substringWithRange(result.rangeAtIndex(i))
            println("\(i): \(substring)")
        }
    }
}

Result:

0: PT00042H42M42S
7: 00042H
8: 00042
9: 42M
10: 42
11: 42S
12: 42
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • Just when you post I find the result with the library : https://github.com/johnno1962/SwiftRegex Thank you for not letting me becoming crazy! – tmato May 06 '15 at 13:42