【发布时间】:2020-01-11 03:44:34
【问题描述】:
我的应用支持 5 种语言。我有一个字符串,其中有一些双引号。该字符串在 localizable.strings 文件中被翻译成 5 种语言。
例子:
title_identifier = "Hi \"how\", are \"you\"";
我想通过查找这些单词的范围来将这个字符串中的“how”和“you”加粗。所以我试图从字符串中提取这些引用的单词,结果将是一个包含“how”和“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"]。我认为这个正则表达式需要添加一些内容,以便在找到两个引号后搜索下一个引号,从而避免引号之间的单词。
【问题讨论】:
-
@wiktor-stribiżew 您建议的重复问题不一样。主要问题是使用 Swift 语言语法来找到正确的正则表达式,而不是任何其他语言。
-
是同一个正则表达式。只需将代码作为有效的 Swift 字符串文字放入。链接帖子中有很多有效的解决方案,见stackoverflow.com/a/1016356/3832970,stackoverflow.com/a/10786066/3832970。
-
在 Swift 代码中表达 double quote 或 backslash 有困难吗?这也已经被问过了。
-
不,我的字符串只是这样的:
var str = "They said \"Its okay\", \"well\" didn't ah ey?"。主要问题是我必须为 swift 类提供一个正则表达式模式:NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\b(a|b)(c|d)\\b" options:NSRegularExpressionCaseInsensitive error:&error];我尝试放入其中的任何正则表达式都会返回一个语法错误 -
matches(for: "\"([^\"]*)\"", in: "Hi \"how\", are \"you\"").map {$0.trimmingCharacters(in: ["\""])}将完成这项工作
标签: swift regex nsattributedstring nsregularexpression