我试图解决Swift 3的问题,但没有成功。
我必须更改此字符串:
< iframe class="giphy-embed" src="//giphy.com/embed/akEhceCKfMyKA"></iframe>
这一个:
< img class="giphy-embed" src="https://media.giphy.com/media/akEhceCKfMyKA/giphy.gif"></img>
节点名称必须从&#39; iframe&#39; 更改为&#39; img&#39; 。此外,我必须保留链接的一部分并更改开头和结尾
&#34; // giphy.com/embed/akEhceCKfMyKA"
至&#34; https://media.giphy.com/media/ akEhceCKfMyKA /giphy.gif"
你有一个正则表达式的解决方案吗?
非常感谢。
答案 0 :(得分:1)
以下是你在Swift中的表现。 NSRegularExpression
仍可与NSString / NSMutableString
一起使用,因此如果您事先进行转换,则会更容易。
let str = "< iframe class=\"giphy-embed\" src=\"//giphy.com/embed/akEhceCKfMyKA\"></iframe>"
let mutableStr = NSMutableString(string: str)
let regex = try! NSRegularExpression(pattern: "<\\s*(iframe).+src=\"(.+?)\".+", options: [])
if let match = regex.firstMatch(in: str, options: [], range: NSMakeRange(0, mutableStr.length)) {
let components = mutableStr.substring(with: match.rangeAt(2)).components(separatedBy: "/")
let newURL = "https://media.giphy.com/media/" + components.last! + "/giphy.gif"
mutableStr.replaceCharacters(in: match.rangeAt(2), with: newURL)
mutableStr.replaceCharacters(in: match.rangeAt(1), with: "image")
}
let newStr = mutableStr as String
答案 1 :(得分:0)
查找
< iframe (class="giphy-embed" src=")\/\/giphy\.com\/embed\/([A-Za-z]*)"><\/iframe>
替换
< img $1https://media.giphy.com/media/$2/giphy.gif"></img>
答案 2 :(得分:0)
感谢Code Different的帮助!
我需要更改一些东西来替换我的字符串中的所有出现。 这是我的代码:
let mutableStr = NSMutableString(string: str)
let regex = try! NSRegularExpression(pattern: "<\\s*(iframe).+src=\"(.+?)\".+(/iframe)", options: [])
let matches = regex.matches(in: str, options: [], range: NSMakeRange(0, mutableStr.length))
var k = matches.count - 1
while k >= 0 {
let match = matches[k]
let components = mutableStr.substring(with: match.rangeAt(2)).components(separatedBy: "/")
let newURL = "https://media.giphy.com/media/" + components.last! + "/giphy.gif"
mutableStr.replaceCharacters(in: match.rangeAt(3), with: "/img")
mutableStr.replaceCharacters(in: match.rangeAt(2), with: newURL)
mutableStr.replaceCharacters(in: match.rangeAt(1), with: "img")
k -= 1
}
print(mutableStr as String)
它完美无缺!