OGeek|极客世界-中国程序员成长平台

标题: ios - RegEx 在 RegexR 中在线工作,但在 NSRegularExpression 中无法在 iOS 上初始化 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 22:19
标题: ios - RegEx 在 RegexR 中在线工作,但在 NSRegularExpression 中无法在 iOS 上初始化

我有一个正则表达式,旨在从 CocoaPods 定义中提取 git URL。

输入文字如下:

pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :branch => 'dev'

正则表达式如下:

(?<=('Alamofire'.*:git => '))[A-Za-z:/\.]+(?=('{1}))

此正则表达式在 RegexR 上正常工作,请参阅 here ,但是当尝试用它初始化 NSRegularExpression 时,会抛出一个错误,代码 2048 表明该模式无效。通常这是由于缺乏逃生,但这里没有。即使在搜索了 iOS 使用的引擎 ICU 正则表达式文档后,我也无法找出问题所在。

TIA,任何想法都会受到欢迎。



Best Answer-推荐答案


您不能在带有 ICU 正则表达式的后向模式中使用长度未知的模式。您的模式在后视中包含 .*,因此它是无效的 ICU regexp (请参阅 由后视模式匹配的可能字符串的长度不能无界(没有 *+ 运算符。) ICU 后视文档部分)。

有两种方式:

这里是方法2,推荐:

let str = "pod 'Alamofire', :git => 'https://github.com/Alamofire/Alamofire.git', :branch => 'dev'"
let rng = NSRange(location: 0, length: str.utf16.count)
let regex = try! NSRegularExpression(pattern: "'Alamofire'.*:git\\s*=>\\s*'([^']+)'")
let matches = regex.matches(in: str, options: [], range: rng)
let group1 = String(str[Range(matches[0].range(at: 1), in: str)!])
print(group1) // => https://github.com/Alamofire/Alamofire.git

regex demo ,绿色突出显示的子字符串是您在第 1 组中获得的值。

图案细节:

关于ios - RegEx 在 RegexR 中在线工作,但在 NSRegularExpression 中无法在 iOS 上初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55038991/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4