用字典中的正确值替换字符串中匹配的正则表达式值

时间:2018-11-01 22:56:05

标签: ios swift regex

我有一个字符串

_maxId = GetMaxId(idCollection);

while (idCollection.Any(id => id == maxId && maxId != 127)
{
    _maxId++;
}

if (_maxId == 127)
{
    // Fail 
}



private int GetMaxId()
{
    return idCollection.Any()
       ? idCollection.Max()
       : 0;
}

和字典

var text = "the {animal} jumped over the {description} fox"

我正在编写一个函数,用字典中的适当值替换大括号中的文本。我想为此使用正则表达式。

var dictionary = ["animal":"dog" , "description", "jumped"]

但是快速的字符串操作对我来说是如此令人困惑,而且这似乎不起作用。

这是正确的方向吗?

谢谢

1 个答案:

答案 0 :(得分:2)

这是一种有效的解决方案。字符串处理甚至更加复杂,因为您还必须处理NSRange

extension String {
    func format(with parameters: [String: Any]) -> String {
        var result = self

        //Handles keys with letters, numbers, underscore, and hyphen
        let regex = try! NSRegularExpression(pattern: "\\{([-A-Za-z0-9_]*)\\}", options: [])

        // Get all of the matching keys in the curly braces
        let matches = regex.matches(in: self, options: [], range: NSRange(self.startIndex..<self.endIndex, in: self))

        // Iterate in reverse to avoid messing up the ranges as the keys are replaced with the values
        for match in matches.reversed() {
            // Make sure there are two matches each
            // range 0 includes the curly braces
            // range 1 includes just the key name in the curly braces
            if match.numberOfRanges == 2 {
                // Make sure the ranges are valid (this should never fail)
                if let keyRange = Range(match.range(at: 1), in: self), let fullRange = Range(match.range(at: 0), in: self) {
                    // Get the key in the curly braces
                    let key = String(self[keyRange])
                    // Get that value from the dictionary
                    if let val = parameters[key] {
                        result.replaceSubrange(fullRange, with: "\(val)")
                    }
                }
            }
        }

        return result
    }
}

var text = "the {animal} jumped over the {description} fox"
var dictionary = ["animal":"dog" , "description": "jumped"]
print(text.format(with: dictionary))

输出:

  

那只狗跳过了跳下的狐狸

如果在词典中找不到原始代码{keyname},则该代码将其留在字符串中。根据需要调整该代码。