试图在 MacOS 上为 swift 中的一个小项目解析 Localizable.string 文件

trying to parse a Localizable.string file for a small project in swift on MacOS

我正在尝试在 MacOS 上为 swift 中的一个小项目解析 Localizable.string 文件。 我只想检索文件中的所有键和值,以便将它们排序到字典中。

为此,我将正则表达式与 NSRegularExpression cocoa class.

结合使用

这些文件如下所示:

"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: [=13=].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 上尝试相同的表达式 \"(.*)\"[ ]*=[ ]*\"(.*)\"; 时,输出是正确的。我做错了什么?

您的函数(来自 ?)匹配 整个模式 只要。如果您对特定的捕获组感兴趣,那么 您必须使用 rangeAt() 访问它们,例如 (尚未更新 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"]

对于任何感兴趣的人,我都可以使用原始功能。我需要它用于 NSDictionary(contentsOf: URL) 不起作用的小型命令行脚本。

func matches(for regex: String, in text: String) -> [String] {
    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        guard let result = regex.firstMatch(in: text, options: [], range: NSRange(location: 0, length: nsString.length)) else {
            return [] // pattern does not match the string
        }
        return (1 ..< result.numberOfRanges).map {
            nsString.substring(with: result.range(at: [=10=]))
        }
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

func getParsedText(text: String) -> [(key: String, text: String)] {
    var dict: [(key: String, text: String)] = []
    let exp = "\"(.*)\"[ ]*=[ ]*\"(.*)\";"

    for line in text.components(separatedBy: "\n") {
        let match = matches(for: exp, in: line)
        if match.count == 2 {
            dict.append((key: match[0], text: match[1]))
        }
    }
    return dict
}

像这样调用它。

let text = try! String(contentsOf: url, encoding: .utf8)

let stringDict = getParsedText(text: text)