0
 func findSrcs(_ content: String) {
            if let match = content.range(of: """
(?<=src=")[^"]+
""", options: .regularExpression) {
                print(content.substring(with: match))
        }
    }

Function above needs to return all srcs in html string. 'Content' is HTML string.
Function works but prints only the first image's src from Content. How to catch all of them?

faris97
  • 402
  • 4
  • 24

1 Answers1

5

You would need to manually find all occurrences in your string using a while condition similar to the one used in this post and get the string subsequences instead of its range:

func findSrcs(_ content: String) -> [Substring] {
    let pattern = #"(?<=src=")[^"]+"#
    var srcs: [Substring] = []
    var startIndex = content.startIndex
    while let range = content[startIndex...].range(of: pattern, options: .regularExpression) {
            srcs.append(content[range])
            startIndex = range.upperBound
    }
    return srcs
}

Playground testing:

let content = """
<span>whatever</span>
<img src="smiley.gif" alt="Smiley face">
<span>whatever</span>
<img src="stackoverflow.jpg" alt="Stack Overflow">
"""

print(findSrcs(content))

This will print

["smiley.gif", "stackoverflow.jpg"]

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571