Swift equivalent to preg_match

I tried to translate the PHP function to Swift. This function is used to format the string according to my regex. So, this is what I am doing 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 am using the $ matches array to format a new String. So in Swift, I found this chain: Swift extract regex matches , which seems to do what I want. But when I get the result, my array is only one line long, my whole 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 is wrong?

Thank you for your responses!

+3


source to share


1 answer


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

If you want to get the corresponding capture groups, you need to use rangeAtIndex:

on 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
+1


source







All Articles