In Swift, I have a string like this
http://mnc-hdqp.oss-cn-shanghai.aliyuncs.com/user%2Fheat%2Fdefault.jpg?Signature=2BI%2BauSvy&Expires=1568682491&OSSAccessKeyId=LTAIQ8Lif1HHVkXd
Need to extract 2BI%2BauSvy
, the value of key Signature
here is code: regex match, then use range to subtract the key ahead.
let key = "Signature"
let signatures = icon.matches(for: "\(key)[^&]+")
guard !signatures.isEmpty else{
return
}
if let range = signatures[0].range(of: "\(key)="){
let signature = String(signatures[0][range.upperBound...])
print(signature)
}
Any way to implement it conveniently?
PS: func matches(for:)
extension String{
func matches(for regex: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: self,
range: NSRange(self.startIndex..., in: self))
return results.map {
String(self[Range($0.range, in: self)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
(?<=Signature=)[^&]+
, is exactly what I want \$\endgroup\$[&?]Signature=([^&#?]+)
is probably closer, using a capture group, or[&?]Signature=(?<sig>[^&#?]+)
to use a named capture group. \$\endgroup\$