user291334
user291334

Reputation: 77

How to filter text?

I have this text:

different text asdasd anasdasdd different text asdsdas @"1 my text" different text different text asdsdas @"2 my text" text different text asdsdas @"3 my text" @"4 my text" asdasd anasdasdd different

I want to filter this text. I want to delete all text except text in quotes. I want to get this result and show this in console:

@"1 my text"
@"2 my text"
@"3 my text"
@"4 my text"

How to do it?

Update:

sometimes my text look like this:

@"1 my \ntext"
@"1 my text"
@"1 \nmy \ntext"
@"\n1 my text"

with character \n

Upvotes: 0

Views: 145

Answers (1)

PPL
PPL

Reputation: 6565

You can do it like this way,

let text = "different text asdasd anasdasdd different text asdsdas @\"1 😂 my text\" different text different text asdsdas @\"2 my text\" text different text asdsdas @\"3 my text\" @\"4 my text\" asdasd anasdasdd different"
let regex = try! NSRegularExpression(pattern:"@\"(.*?)\"", options: .dotMatchesLineSeparators)
var results = [String]()

regex.enumerateMatches(in: text, options: [], range: NSMakeRange(0, text.utf16.count)) { result, flags, stop in
    if let r = result?.range(at: 1), let range = Range(r, in: text) {
        results.append(String(text[range]))
    }
}

print(results)

Output will be like this,

["1 😂 my text", "2 my text", "3 my text", "4 my text"]

FYI. You can create extension for the above function too for code optimization.

Upvotes: 3

Related Questions