"regex सहायक समारोह" का उपयोग 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 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]
पैटर्न "\d+"
मैचों में एक या अधिक दशमलव अंक के साथ आसानी से प्राप्त कर सकते हैं।
पाठ्यक्रम एक ही के
अगर आप पसंद करते एक सहायक समारोह के उपयोग के बिना किया जा सकता है कि जो भी कारण के लिए:
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]
:
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]
वैकल्पिक समाधान नियमित अभिव्यक्ति के बिना
जांच करने के लिए इस पोस्ट स्ट्रिंग आइटम को int http में कैसे परिवर्तित करें: //stackoverflow.com/questions/24115141/swift-converting-string-to-int – Schuere
एक दें: Int? = str.toInt() मुझे एक शून्य मूल्य देता है .. – alphonse