所以我有一个图片网址:
https://images.gr-assets.com/books/1410762334m/135625.jpg
我想在第一个数字块(1410762334)之后用字母“l”更改字母“m”。
我尝试使用replacingOccurrences(of: "m", with: "l", options: .literal, range: nil)
,正如预期的那样,它将所有m替换为l并且不起作用。我知道它与范围有关,但我不确定该放置什么范围。请赐教:))
提前致谢!
答案 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"
}