acoustickat acoustickat - 1 year ago 106
Swift Question

How can I replace a single character of a URL from a string that contains many such characters in Swift 3?

So I have an image URL:

https://images.gr-assets.com/books/1410762334m/135625.jpg


And I want to change the letter "m" after the first block of numbers (1410762334) with the letter "l".

I tried using
replacingOccurrences(of: "m", with: "l", options: .literal, range: nil)
and as expected, it replaces all m's with l's and it doesn't work. I know it's got to do with the range but I'm not sure what to put as the range. Please enlighten me :)

Thanks in advance!

Answer Source

You should use NSRegularExpression for this.

  • Firstly, this code searches for a numeric value followed by the letter m and a slash (/).
  • After that, it searches for m in only that range and replaces it with an l.

let urlString: NSString = "https://images.gr-assets.com/books/1410762334m/135625.jpg"

do {
    let regex = try NSRegularExpression(pattern: "[0-9]m/", options: .caseInsensitive)

    let fullRange = NSMakeRange(0, urlString.length)
    let matchRange = regex.rangeOfFirstMatch(in: urlString as String, options: [], range: fullRange)

    let modString = urlString.replacingOccurrences(of: "m", with: "l", options: .caseInsensitive, range: matchRange)
} catch let error {
    //NSRegularExpression threw an error; handle it properly
    print(error.localizedDescription)
}

Swift 4

let urlString = "https://images.gr-assets.com/books/1410762334m/135625.jpg"

do {
    let regex = try NSRegularExpression(pattern: "[0-9]m/", options: .caseInsensitive)

    let fullRange = NSMakeRange(0, urlString.count)
    let matchRange = regex.rangeOfFirstMatch(in: urlString, options: [], range: fullRange)

    let modString = urlString.replacingOccurrences(of: "m", with: "l", options: .caseInsensitive, range: Range(matchRange, in: urlString))
} catch let error {
    //NSRegularExpression threw an error; handle it properly
    print(error.localizedDescription)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download