Regex for Validating Custom URL Schemes in Swift - implementing Optional Query Parameters
I'm working on a project and hit a roadblock. I'm working on a Swift application that needs to validate custom URL schemes... The URLs can have an optional query string at the end, but I'm running into issues with properly matching these optional segments. The format I'm trying to validate is: `myapp://resource?id=123&name=test` or `myapp://resource`. I've tried the following regex: ```swift let urlPattern = "^myapp://resource(\?id=\d+&name=[a-zA-Z]+)?$" ``` However, this doesn't seem to capture the optional query parameters correctly. When I test it with the second example (`myapp://resource`), I get unexpected results. I receive a failure instead of a successful match. I've also attempted to make the query parameters optional by using the `?` quantifier, but it seems the regex is still overly picky about the formatting. Can anyone guide to refine this regex so that it properly validates both URL formats? Additionally, are there any best practices in regex for handling optional segments like this, especially in Swift? I'm using Swift 5.7 and the following validation code: ```swift let regex = try! NSRegularExpression(pattern: urlPattern, options: []) let matches = regex.matches(in: url, options: [], range: NSRange(location: 0, length: url.utf16.count)) if matches.count > 0 { print("Valid URL") } else { print("Invalid URL") } ``` Any insights or alternative approaches would be greatly appreciated. I'm on CentOS using the latest version of Swift. The project is a CLI tool built with Swift. Is this even possible?