douzhuozhu9544 2015-05-06 12:45
浏览 37
已采纳

在Swift中等效的preg_match

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!

  • 写回答

1条回答 默认 最新

  • doujieyu7062 2015-05-06 13:31
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么