我需要从字符串中获取字符串数组,例如从此字符串中
"1. Grease cake pans with oil spray and preheat your oven to 350°F.2. Dissolve the coffee powder in the hot water.3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."
到
["1. Grease cake pans with oil spray and preheat your oven to 350°F.",
"2. Dissolve the coffee powder in the hot water."
"3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."]
在正常情况下,基于字符串中的数字
String.components(separatedBy: <#T##CharacterSet#>)
工作正常,但在这种情况下我无法弄清楚。提前致谢
您可以尝试匹配任何数字(1 个或多个)后跟一个点和一个空格。那么除了一个句号后跟一个句号之外的任何东西:
let string = "1. Grease cake pans with oil spray and preheat your oven to 350°F.2. Dissolve the coffee powder in the hot water.3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."
let pattern = #"\d{1,}. {1}[^.]+.{1}"#
let sentences = try! NSRegularExpression(pattern: pattern)
.matches(in: string, range: .init(string.startIndex..., in: string))
.map { string[Range($0.range, in: string)!] }
print(sentences) // "["1. Grease cake pans with oil spray and preheat your oven to 350°F.", "2. Dissolve the coffee powder in the hot water.", "3. Combine the flour with cocoa powder, sugar, baking powder, baking soda, salt oil, buttermilk, eggs, in a large bowl."]\n"
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句