TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Broken range for regular expression

Forums > Swift

@Cordt  

Hey,

I have a problem with a regular expression. I am trying to match an image URL in a string with the following pattern:

let imageName = "img/background.jpg"
let pattern = #"url\(['"]?(..\/)*(img\/background.jpg)['"]?\);"#

Trying to iterate through the matches

func findImageUrls(in: String, using pattern: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: pattern, options: [])
        print(regex.pattern)
        let stringRange = NSRange(location: 0, length: `in`.utf8.count)
        let matches = regex.matches(in: `in`, range: stringRange)
        var result: [[String]] = []
        for match in matches {
            var groups: [String] = []
            for rangeIndex in 1 ..< match.numberOfRanges {
                groups.append((`in` as NSString).substring(with: match.range(at: rangeIndex)))
            }
            if !groups.isEmpty {
                result.append(groups)
            }
        }
        return result.flatMap { $0 }

    } catch let error {
        print(error)
        return []
    }
}

produces a crash. The reason is that match.range(at: rangeIndex) produces an invalid range: {9223372036854775807, 0}.

I verified that the regex is working on Regex101 and read Paul's article on raw strings.

I have a feeling something about the escaping is not right :) Anyone has an idea what's wrong?

Thanks!

Cordt

2      

@Cordt  

Found the problem: The quantifier needs to be inside the capturing group, not outside:

let pattern = #"url\(['"]?(../*)(img\/background.jpg)['"]?\);"#

Interestingly, regex101 doesn't complain. But Swift does :)

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.