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 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?