【问题标题】:preg_match equivalent in SwiftSwift 中的 preg_match 等价物
【发布时间】:2015-05-06 21:31:03
【问题描述】:

我试图将一个 PHP 函数翻译成 Swift。该函数用于根据我的正则表达式将字符串格式化为另一个字符串。所以这就是我在 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)

我使用 $matches 数组来格式化我的新字符串。 所以,在 Swift 中,我找到了这个线程:Swift extract regex matches,这似乎符合我的要求。但是当我得到结果时,我的数组只有一个字符串长,我的整个输入......

    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]

你知道怎么回事吗?

感谢您的回答!

【问题讨论】:

    标签: php regex swift


    【解决方案1】:

    数组包含一个元素,因为输入正好包含一个与模式匹配的字符串“PT00042H42M42S”。

    如果您想检索匹配的捕获组,那么您必须 在NSTextCheckingResult 上使用rangeAtIndex:。示例:

    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)")
            }
        }
    }
    

    结果:

    0:PT00042H42M42S 7:00042H 8:00042 9:42M 10:42 11:42秒 12:42

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 2014-07-23
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    相关资源
    最近更新 更多