Swift: 從一定格式的字串中擷取資料返回(正則表示式方式)
阿新 • • 發佈:2018-12-31
A. 輸入要擷取的字串,返回一個目標輸出引數的字串陣列
1.輸入輸出引數:
1. input str = "raw=281804 mV level=100.00%"
2. output battaryArray[0] = "281804"
battaryArray[1] = "100.00%";
2.方法實現:
/// getBatteryParamsFromString---->[String] /// # getBatteryParams: /// 1. batteryValue 2. batteryLevel /// # example: /// 1. input str = "raw=281804 mV level=100.00%" /// 2. output battaryArray[0] = "281804" /// battaryArray[1] = "100.00%"; /// /// - Parameter str: String /// - Returns: [String] private func getBatteryParams(str: String) -> [String]{ var batteryArray = [String]() let batteryValueKey = "raw=" let batteryLevelKey = "level=" let substringArry = (str as NSString).components(separatedBy: " "); assert(substringArry.count > 0, "Get the BatteryParams Fail") for sub:String in substringArry { //print(sub); let substring = (sub as NSString).contains(batteryValueKey) if substring { batteryArray.append((sub as NSString).substring(with: NSMakeRange(batteryValueKey.count, sub.count-batteryValueKey.count))) }else { if sub.contains(batteryLevelKey) { batteryArray.append((sub as NSString).substring(with: NSMakeRange(batteryLevelKey.count, sub.count-batteryLevelKey.count))) } } } return batteryArray }
B. 輸入要擷取的字串,返回一個目標輸出引數的Float陣列(正則表示式)
1.輸入輸出引數:
1. input str = "raw=281804 mV level=100.00%"
swift 中對應的正則表示式"raw=(\\d+) mV level=(\\d+(?:\\.\\d+)?)%"
2. output battaryArray[0] = "281804"
battaryArray[1] = "100";
2.方法實現:
/// getBatteryParamsFromString---->[Float] /// # getBatteryParams: /// 1. batteryValue 2. batteryLevel /// # example: /// 1. input str = "raw=281804 mV level=100.00%" /// 2. output battaryArray[0] = "281804" /// battaryArray[1] = "100"; /// /// - Parameter str: String /// - Returns: [Float] private func getBatteryParams(str: String) -> [Float]{ let regex = try! NSRegularExpression(pattern: "raw=(\\d+) mV level=(\\d+(?:\\.\\d+)?)%", options: []) let matches = regex.matches(in: str, options: [], range: NSRange(str.startIndex..., in: str)) assert(matches.count > 0, "Get the BatteryParams Fail") var resultArray: [String] = [] for match in matches { // let str1 = String(str[Range(match.range(at: 1), in: str)!]) // let str2 = String(str[Range(match.range(at: 2), in: str)!]) // resultArray.append(str1) // resultArray.append(str2) resultArray.append(contentsOf: [String(str[Range(match.range(at: 1), in: str)!]), String(str[Range(match.range(at: 2), in: str)!])]) } let result: [Float] = resultArray.map({Float($0)!}) return result }