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.

1

2 Answers 2

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("@!") }
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the input, this return the following 'use of unresolved indentifier 'CharacterSet'
That’s Swift 3. Update your Xcode or try to replace it with NSCharacterSet.
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.