regex - 试图在 MacOS 上快速解析一个小项目的 Localizable.string 文件

标签 regex swift string macos nsregularexpression

我正在尝试在 MacOS 上快速解析一个小型项目的 Localizable.string 文件。
我只想检索文件中的所有键和值以将它们分类到字典中。

为此,我将正则表达式与 NSRegularExpression 一起使用。 cocoa 类。

这是这些文件的样子:

"key 1" = "Value 1";
"key 2" = "Value 2";
"key 3" = "Value 3";

这是我的代码,它应该从加载到 String 的文件中获取键和值。 :
static func getDictionaryFormText(text: String) -> [String: String] {
    var dict: [String : String] = [:]
    let exp = "\"(.*)\"[ ]*=[ ]*\"(.*)\";"

    for line in text.components(separatedBy: "\n") {
        let match = self.matches(for: exp, in: line)
        // Following line can be uncommented when working
        //dict[match[0]] = match[1]
        print("(\(match.count)) matches = \(match)")
    }
    return dict
}

static 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 as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

使用提供的 Localizable 示例运行此代码时,输​​出如下:
(1) matches = ["\"key 1\" = \"Value 1\";"]
(1) matches = ["\"key 2\" = \"Value 2\";"]
(1) matches = ["\"key 3\" = \"Value 3\";"]

听起来比赛在第一个 " 之后并没有停止发生。当我尝试相同的表达式时 \"(.*)\"[ ]*=[ ]*\"(.*)\";在 regex101.com 上,输出是正确的。我究竟做错了什么 ?

最佳答案

您的函数(来自 Swift extract regex matches ?)匹配整个模式
只要。如果您对特定的捕获组感兴趣,那么
您必须使用 rangeAt() 访问它们例如在
Convert a JavaScript Regex to a Swift Regex (尚未针对 Swift 3 进行更新)。

然而,有一个更简单的解决方案,因为 .strings 文件实际上使用了一种可能的属性列表格式,并且
可以直接读入字典。例子:

if let url = Bundle.main.url(forResource: "Localizable", withExtension: "strings"),
    let stringsDict = NSDictionary(contentsOf: url) as? [String: String] {
    print(stringsDict)
}

输出:
["key 1": "Value 1", "key 2": "Value 2", "key 3": "Value 3"]

关于regex - 试图在 MacOS 上快速解析一个小项目的 Localizable.string 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39705576/

相关文章:

c - ispalindrome C,检查空间的问题

python - 当某些条目需要从不同位置拆分时,如何按连续空格拆分

ios - 如何在 Swift4 中获取另一个类的枚举内容?

swift - NSBezierPath 绘制方向错误

swift - AVAssetReader输出内存问题

c# - 打印为 PDF 时字符串格式中的退格键

java - 字符串加倍,然后再返回。 ( java )

java - 我如何在 Java 中使用正则表达式查找字符串的最后六位数字?

javascript - 使用正则表达式我们可以取偶数位和奇数位的值吗?

regex - 用于重新排序字段中字符串的正则表达式