Kayla tucker
Kayla tucker

Reputation: 61

Extract text from Swift string

I have an array of strings and I want to extract only what's inside <>.

<div class=\"name\" title=\"&quot;User&quot; <John Appleseed>\">
<div class=\"name\" title=\"&quot;User&quot; <Bill Gates>\">

So the result I expect is ["John Appleseed", "Bill Gates"]

Upvotes: 0

Views: 240

Answers (1)

Joakim Danielson
Joakim Danielson

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=\"&quot;User&quot; <John Appleseed>\">", "<div class=\"name\" title=\"&quot;User&quot; <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

Related Questions