Swift 中的 preg_match 等效项

2024-05-24

我尝试将 PHP 函数转换为 Swift。该函数用于根据 my 正则表达式将字符串格式化为另一个字符串。这就是我在 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 提取正则表达式匹配 https://stackoverflow.com/questions/27880650/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]

你知道出了什么问题吗?

谢谢您的回答!


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

如果你想检索匹配的捕获组那么你必须 使用rangeAtIndex: on the NSTextCheckingResult。例子:

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
  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Swift 中的 preg_match 等效项 的相关文章

随机推荐