在 Swift 中,我想提取 Prefix until space 和 Suffix until 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"