0

I'm looking for a way to loop through a string and pull out words into an array where a certain prefix and suffix is contained.

For example, lets take the following string;

let str = "A Lorem @!ipsum!@ dolor sit amet, @!consectetur!@ adipiscing elit" 

I need a way to search the text and output both the words ipsum and consectetur into an array to be used within another function later on.

vaibhav
  • 4,038
  • 1
  • 21
  • 51
ScoopMatt
  • 79
  • 2
  • 7

2 Answers2

2

How about this?

let input = "A Lorem @!ipsum!@ dolor sit amet, @!consectetur!@ adipiscing elit."
let words = input.components(separatedBy: CharacterSet.whitespacesAndNewlines)
let interesting = words.filter { $0.hasPrefix("@!") }
zoul
  • 102,279
  • 44
  • 260
  • 354
0

Use regular expression:

let text = "A Lorem @!ipsum!@ dolor sit amet, @!consectetur!@ adipiscing elit."
let pattern = "@!(\\w+)!@"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count))
let array = matches.map({(text as NSString).substring(with: $0.rangeAt(1))})
print(array)
vadian
  • 274,689
  • 30
  • 353
  • 361