我的应用程序支持5种语言。我有一个字符串,其中有一些双引号。该字符串在localizable.strings文件中翻译成5种语言。
例:
title_identifier = "Hi \"how\", are \"you\"";
我想通过查找这些单词的范围来加粗该字符串中的“如何”和“您”。因此,我试图从字符串中提取这些带引号的单词,结果将是一个包含“如何”和“您”或其范围的数组。
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
matches(for: "(?<=\")[^\"]*(?=\")", in: str)
结果是:["how", ", are ", "you"]
而不是["how","you"]
。我认为此正则表达式需要一些补充,以便一旦找到两个引号就可以搜索下一个引号,从而避免引号之间的单词。
您的问题是使用了不消耗文本但要检查其模式是否匹配并返回true或false的环顾四周。查看运行中的正则表达式,进行, are
匹配,因为"
前一个匹配中的最后一个未被消耗,正则表达式索引w
紧随其后,因此下一个匹配可以以开头"
。您需要使用消耗这里模式,"([^"]*)"
。
但是,您的代码将仅返回完全匹配项。您可以在"
此处用修剪第一个和最后一个.map {$0.trimmingCharacters(in: ["\""])}
,因为正则表达式仅在开头和结尾匹配一个引号:
matches(for: "\"[^\"]*\"", in: str).map {$0.trimmingCharacters(in: ["\""])}
这是正则表达式演示。
可替换地,访问组1个值通过追加(at: 1)
后$0.range
:
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range(at: 1), in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
let str = "Hi \"how\", are \"you\""
print(matches(for: "\"([^\"]*)\"", in: str))
// => ["how", "you"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句