gpt4 book ai didi

ios - 正则表达式在 Swift 中获取方括号对之间的文本

转载 作者:行者123 更新时间:2023-11-29 05:21:36 24 4
gpt4 key购买 nike

<strong>Lorem Ipsum.<\/strong> Lorem Ipsum. [link-to:shop-page \"instore-pickup\"]Learn More[\/link-to]

给定上面的示例字符串(它包括 HTML),它是我从第 3 方服务获得的,并且我无法控制改进或规范化它以适应 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 []
}
}

最佳答案

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。

关于ios - 正则表达式在 Swift 中获取方括号对之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58634799/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com