-6

在 Swift 中,我想提取 Prefix until space 和 Suffix until space 都用“:”分隔。如果字符串之间有空格,它应该是下一行。前任:

Apple: Fruit Tomato: Vegetable Iron: Material

结果需要作为

Apple: Fruit
Tomato: Vegetable
Iron: Material

请提供任何帮助

4

1 回答 1

0

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

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"
于 2018-01-01T21:43:23.223 回答