-6

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

Sureshtrb
  • 51
  • 11

1 Answers1

1

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571