【发布时间】: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]
你知道怎么回事吗?
感谢您的回答!
【问题讨论】: