Extracting Specific Strings From Text

I am trying to extract specific strings from my text. I have a string similar to this:

"blablabla(/)Hello Bob(|)bla(/)Hi(|)blablaba"

and I am trying to concatenate a string array of text between (/) and (|) but I cannot figure out a efficient way to do this. In this example I would want to return "Hello Bob" and "Hi". How can I effectively extract specific strings from a string in Swift?

Upvotes: 0

Views: 307

Answers (1)

Antonio
Antonio

Reputation: 72780

Using a functional approach, you can:

  • split the string by (/), which returns an array of strings
  • for each element of the array, transform it into an array of strings split by (|)
  • filter the resulting array including only values (arrays) having more than one element
  • transform each element (array) of the resulting array into its first element

This is the code:

let array = string.componentsSeparatedByString("(/)")
    .map { $0.componentsSeparatedByString("(|)") }
    .filter { $0.count > 1 }
    .map { $0[0] }

Given this input string:

let string = "blablabla(/)Hello Bob(|)bla(/)Hi(|)blablaba"

the result is:

["Hello Bob", "Hi"]

Upvotes: 2

Related Questions