简体   繁体   English

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

[英]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" . 我想在数字的第一块(1410762334)之后将字母“ m”更改为字母“ 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. 我尝试使用replacingOccurrences(of: "m", with: "l", options: .literal, range: nil)并按预期的那样,将所有m替换为l,但不起作用。 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! 提前致谢!

You should use NSRegularExpression for this. 您应该为此使用NSRegularExpression

  • Firstly, this code searches for a numeric value followed by the letter m and a slash ( / ). 首先,此代码搜索一个数字值,后跟字母m和一个斜杠( / )。
  • After that, it searches for m in only that range and replaces it with an l . 之后,它仅在该范围内搜索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 斯威夫特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)
}

For this answer I'm going to assume that the number part before the m is the only dynamic part of the URL. 对于这个答案,我将假设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"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM