Reputation: 61
I have an array of strings and I want to extract only what's inside <>.
<div class=\"name\" title=\""User" <John Appleseed>\">
<div class=\"name\" title=\""User" <Bill Gates>\">
So the result I expect is ["John Appleseed", "Bill Gates"]
Upvotes: 0
Views: 240
Reputation: 51831
If you have filtered out the correct rows and the structure of the string is the same you can use lastIndex(of:)
and firstIndex(of:)
functions to find the inner <> pair and then extract a substring from that
if let first = str.lastIndex(of:"<"), let last = str.firstIndex(of:">") {
let name = String(str[str.index(after: first)..<last])
}
Example
let strings = ["<div class=\"name\" title=\""User" <John Appleseed>\">", "<div class=\"name\" title=\""User" <Bill Gates>\">"]
for str in strings {
if let first = str.lastIndex(of:"<"), let last = str.firstIndex(of:">") {
let name = String(str[str.index(after: first)..<last])
print(name)
}
}
produces
John Appleseed
Bill Gates
Upvotes: 1