如何从Swift 3中包含许多此类字符的字符串替换URL的单个字符?

时间:2017-10-02 15:19:55

标签: swift

所以我有一个图片网址:

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

我想在第一个数字块(1410762334)之后用字母“l”更改字母“m”

我尝试使用replacingOccurrences(of: "m", with: "l", options: .literal, range: nil),正如预期的那样,它将所有m替换为l并且不起作用。我知道它与范围有关,但我不确定该放置什么范围。请赐教:))

提前致谢!

2 个答案:

答案 0 :(得分:0)

您应该使用NSRegularExpression

  • 首先,此代码搜索数字值,后跟字母m和斜杠(/)。
  • 之后,它仅在该范围内搜索m,并将其替换为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)
}

答案 1 :(得分:0)

对于这个答案,我将假设m之前的数字部分是URL的唯一动态部分。

import Foundation

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

if let range = url.range(of: "^https://images.gr-assets.com/books/[0-9]*", options: .regularExpression) {
  let changedUrl = "\(url[range])l/135625.jpg"
}