字符串前缀和后缀在Swift中用“:”分隔

时间:2018-01-01 18:22:05

标签: arrays swift prefix suffix

在Swift中我想提取前缀直到空格和后缀,直到空格都被“:”分隔。如果字符串之间的空格应该是下一行。 例如:

Apple: Fruit Tomato: Vegetable Iron: Material

结果需要

Apple: Fruit
Tomato: Vegetable
Iron: Material

请帮助

1 个答案:

答案 0 :(得分: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"