ios - 在 iOS Swift 中使用正则表达式提取值

标签 ios iphone swift

我想从它的 URL 中提取 Vimeo Id。我尝试了很多解决方案,但没有找到我真正想要的 swift。我引用了很多问题并在 JAVA 中找到了一个解决方案。我希望在 iOS swift 中有相同的行为,这样我就可以从匹配的组数组中提取 ID。

Using Regular Expressions to Extract a Value in Java

我使用以下 vimeo URL 正则表达式,如果字符串与正则表达式匹配,我想要 group-3:

[http|https]+:\/\/(?:www\.|player\.)?vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/([^\/]*)\/视频\/|专辑\/(\d+)\/视频\/|视频\/|)([a-zA-Z0-9_\-]+)(& .+)?”

测试 Vimeo 网址:https://vimeo.com/62092214?query=foo

最佳答案

let strToTest = "https://vimeo.com/62092214?query=foo"

let pattern = "[http|https]+:\\/\\/(?:www.|player.)?vimeo.com\\/(?:channels\\/(?:\\w+\\/)?|groups\\/([^\\/]*)\\/videos\\/|album\\/(\\d+)\\/video\\/|video\\/|)([a-zA-Z0-9_\\-]+)(&.+)?"

let regex = try! NSRegularExpression.init(pattern: pattern, options: [])
let match = regex.firstMatch(in: strToTest, options: [], range: NSRange.init(location: 0, length: strToTest.count))
let goup3Range = match?.range(at: 3)
let substring = (strToTest as NSString).substring(with: goup3Range!)
print("substring: \(substring)")

这应该有效。

您需要转义模式中的所有\
您需要调用 range(at:) 以根据您的模式(当前为 group3)获取您想要的组的范围,然后是子字符串。

应该改进什么?
好吧,我做了各种力解包(每次我写一个 !)。为了逻辑,不要添加do/catchif let等。我强烈建议您仔细检查它们。

关于ios - 在 iOS Swift 中使用正则表达式提取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49359841/

相关文章:

iphone - AVAudioPlayer 不使用 ARC 释放内存

iphone - 将 UIWebview 内容转换为 UIImage

ios - 将另一个 View Controller 加载到 UItabbarcontroller

ios - 如何使 MGLPolyline 可点击?

ios - 相同的日期...但不同?也许时区困惑

iphone - 递归地将 self.view 添加到 self.view 中?

ios - 如何沿 UIBezierPath 仅对完整 CALayer 动画的一部分进行动画处理?

iphone - 将 iPhone 挂载为磁盘

objective-c - 在 UITableView 中使用插入行

JSON 数据未传递到 tableView Cell