Swift 中的字符串前缀和后缀以“:”分隔

String prefix and Suffix separated by ": " in Swift

在 Swift 中,我想提取 space 之前的前缀和 space 之前的后缀,两者都用“:”分隔。如果字符串之间的白色 space 它应该是下一行。 例如:

Apple: Fruit Tomato: Vegetable Iron: Material

结果需要

Apple: Fruit
Tomato: Vegetable
Iron: Material

请帮忙

您可以使用正则表达式 "(?<!:) " 来替换 " " 处没有冒号标点符号的空格 ":":

let string = "Apple: Fruit Tomato: Vegetable Iron: Material"
let pattern = "(?<!:) "
let result = string.replacingOccurrences(of: pattern, with: "\n", options: .regularExpression)
print(result)    // "Apple: Fruit\nTomato: Vegetable\nIron: Material\n"