Sử dụng "chức năng helper regex" từ 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)}
}
bạn có thể đạt được điều đó một cách dễ dàng với
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let numbersAsStrings = matchesForRegexInText("\\d+", str) // [String]
let numbersAsInts = numbersAsStrings.map { $0.toInt()! } // [Int]
println(numbersAsInts) // [3, 7, 10]
Các mô hình "\d+"
trận đấu một hoặc chữ số thập phân hơn.
Tất nhiên tương tự có thể được thực hiện mà không cần dùng một hàm helper nếu bạn thích rằng vì lý do gì:
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let regex = NSRegularExpression(pattern: "\\d+", options: nil, error: nil)!
let nsString = str as NSString
let results = regex.matchesInString(str, options: nil, range: NSMakeRange(0, nsString.length))
as! [NSTextCheckingResult]
let numbers = map(results) { nsString.substringWithRange($0.range).toInt()! }
println(numbers) // [3, 7, 10]
giải pháp thay thế mà không biểu thức thông thường:
let str = "I have to buy 3 apples, 7 bananas, 10eggs"
let digits = ""
let numbers = split(str, allowEmptySlices: false) { !contains(digits, $0) }
.map { $0.toInt()! }
println(numbers) // [3, 7, 10]
kiểm tra bài này cho làm thế nào để chuyển đổi một mục chuỗi thành int http: //stackoverflow.com/questions/24115141/swift-converting-string-to-int – Schuere
let a: Int? = str.toInt() mang lại cho tôi một giá trị nil .. – alphonse