ios - 用字典中的正确值替换字符串中匹配的正则表达式值
问题描述
我有一个字符串
var text = "the {animal} jumped over the {description} fox"
和一本字典
var dictionary = ["animal":"dog" , "description", "jumped"]
我正在编写一个函数,用字典中的适当值替换花括号中的文本。我想为此使用正则表达式。
//alpha numeric characters, - and _
let regex = try NSRegularExpression(pattern: "{[a-zA-Z0-9-_]}", options: .caseInsensitive)
var text = "the {animal} jumped over the {description} fox"
let all = NSRange(location: 0, length: text.count)
regex.enumerateMatches(in: text, options: [], range: all) { (checkingResult, matchingFlags, _) in
guard let resultRange = checkingResult?.range else {
print("error getting result range")
return
}
//at this point, i was hoping that (resultRange.lowerbound, resultRange,upperBound) would be the start and end index of my regex match.
//so print(text[resultRange.lowerBound..<resultRange.upperBound] should give me {animal}
//so i could get the word between the curly braces, and replace it in the sentence with it dictionary value
}
但是快速的字符串操作让我非常困惑,这似乎不起作用。
这是正确的方向吗?
谢谢
解决方案
这是一种有效的解决方案。字符串处理更加复杂,因为您还必须处理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}
如果在字典中找不到此代码,则将原始代码保留在字符串中。根据需要调整该代码。
推荐阅读
- gem5 - 警告:在简单 gem5 模拟期间忽略系统调用 mprotect(...)
- c++ - 如何在 C 代码上从终端运行 Google 测试?
- c# - 如何修复我的行星重力脚本?(C#)
- python - 使用 PsExec 时如何在 pythonsub 进程中访问标准输入和标准输出
- php - SMTP PHPMailer 连接被拒绝 (111)
- javascript - 每 5 秒比较页面上的图像
- html - 以 flex-direction: column 包裹时,Flexbox 滚动中断
- c# - System.Text.Json.JsonException:无法将 Json 转换为 DataModel
- r - 在 R 中重新创建 Excel 数据透视表 - 表格或 qpvt
- javascript - 如何使用cheerio.js 获取图像src?