【发布时间】:2019-07-26 08:20:14
【问题描述】:
我有一个字符串扩展名:
extension String {
func split(usingRegex pattern: String) -> [String] {
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: self, range: NSRange(0..<utf16.count))
let ranges = [startIndex..<startIndex] + matches.map{Range($0.range, in: self)!} + [endIndex..<endIndex]
return (0...matches.count).map {String(self[ranges[$0].upperBound..<ranges[$0+1].lowerBound])}
}
}
我是这样使用它的:
var string = "Hello45playground23today"
var output = string.split(usingRegex: "[0-9]+")
输出是:
["Hello", "playground", "today"]
但我需要的是:
["Hello", "45", "playground", "23", "today"]
有没有办法在 Swift 中实现这一点?
【问题讨论】:
-
可以选择正则表达式吗?