0

I have the following array

["<h1>Test</h1><h2>Test2</h2>", "<h3>Hello, playground</h3>Testing", "<h3>Test</h3>", "<h2>Main Takeaway</h2>"]

I want to get all the values between <h3> and </h3> as well as <h2> and </h2>. So I want to create an array with the following values

Hello, playground,
Test
Main Takeaway

How do I do that?

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165

1 Answers1

1

Use a regular expression to find and replace the values within the h2/h3 tags

let array = ["<h1>Test</h1><h2>Test2</h2>", "<h3>Hello, playground</h3>Testing", "<h3>Test</h3>", "<h2>Main Takeaway</h2>"]

let values = array.map { $0.replacingOccurrences(of: #".*(<h2>|<h3>)(.*)(</h2>|</h3>).*"#, with: "$2", options: .regularExpression) }
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
  • This will return the whole string if there are no `h2/h3` tags, maybe an empty string would've been a better candidate. Also, in case there are multiple tags within the same string, then this will match only one of them. Another corner case is with strings like `

    text`, the regex will match these invalid combinations too.

    – Cristik Jun 12 '21 at 12:18