Search code examples
arraysswiftprefixsuffix

String prefix and Suffix separated by ": " in Swift


In Swift I want to extract the Prefix until space and Suffix until space both separated by ": ". If white space between strings it should be next line. Ex:

Apple: Fruit Tomato: Vegetable Iron: Material

Result needed as

Apple: Fruit
Tomato: Vegetable
Iron: Material

Any help please


Solution

  • You can use regular expression "(?<!:) " to replace the white spaces " " occurrences where it is not preceded by colon punctuation ":":

    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"