UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.