<strong>Lorem Ipsum.<\/strong> Lorem Ipsum. [link-to:shop-page \"instore-pickup\"]Learn More[\/link-to]
给出上面的示例字符串(包括HTML),该字符串是我从第三方服务获得的,因此无法改善或标准化它以适合HTML标准。
我需要以某种方式解析[link-to:shop-page \"instore-pickup\"]Learn More[\/link-to]
的这一部分,以获取Learn More
的值。
我已经尝试过\\[.*?\\](.*?)\\[.*?\\]
正则表达式,但是它不能满足我的需要。
得到[link-to:shop-page \"instore-pickup\"]Learn More[/link-to]
的结果。
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
答案 0 :(得分:0)
维克多(Wiktor),感谢您指出这一点,有效的代码段:
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range(at: 1))}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
$0.range(at: 1)
分配组1。