【问题标题】:Find multiple quoted words in a string with regex使用正则表达式在字符串中查找多个引用的单词
【发布时间】: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/3832970stackoverflow.com/a/10786066/3832970
  • 在 Swift 代码中表达 double quotebackslash 有困难吗?这也已经被问过了。
  • 不,我的字符串只是这样的: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:&amp;error]; 我尝试放入其中的任何正则表达式都会返回一个语法错误
  • matches(for: "\"([^\"]*)\"", in: "Hi \"how\", are \"you\"").map {$0.trimmingCharacters(in: ["\""])} 将完成这项工作

标签: swift regex nsattributedstring nsregularexpression


【解决方案1】:

您的问题在于使用不使用文本但检查其模式是否匹配并返回 truefalse 的环视。参见your regex in action, are 匹配,因为上一场比赛中的最后一个" 没有被消耗,正则表达式索引仍然在w 之后,所以下一场比赛可以从" 开始。您需要在此处使用 消费 模式,"([^"]*)"

但是,您的代码只会返回完全匹配的内容。您可以在此处使用.map {$0.trimmingCharacters(in: ["\""])} 修剪第一个和最后一个"s,因为正则表达式仅匹配开头和结尾的一个引号:

matches(for: "\"[^\"]*\"", in: str).map {$0.trimmingCharacters(in: ["\""])}

这里是regex demo

或者,通过在 $0.range 之后附加 (at: 1) 来访问组 1 值:

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"]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2019-01-20
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多