iosarraysswiftstring

(Swift) How to find all strings that matches regex in string


 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?


Solution

  • edit/update:

    We can use the new Swift native Regex Component and get all matches of a regex. Unfortunately it doesn't support lookbehind but we can do something like:

    let content = """
    <span>whatever</span>
    <img src="smiley.gif" alt="Smiley face">
    <span>whatever</span>
    <img src="stackoverflow.jpg" alt="Stack Overflow">
    """
    
    let matches = content
        .matches(of: /<img.+?src=[\"'](.+?)[\"'].*?>/)
        .map(\.output.1)
    
    print(matches) // ["smiley.gif", "stackoverflow.jpg"]
    

    original post

    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:

    print(findSrcs(content))
    

    This will print

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