Find multiple quoted words in a string with regex

后端 未结 1 628
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 13:26

My app supports 5 languages. I have a string which has some double quotes in it. This string is translated into 5 languages in the localizable.strings files.

Example

相关标签:
1条回答
  • 2020-12-21 14:08

    Your problem is in the use of lookarounds that do not consume text but check if their patterns match and return either true or false. See your regex in action, the , are matches because the last " in the previous match was not consumed, the regex index remained right after w, so the next match could start with ". You need to use a consuming pattern here, "([^"]*)".

    However, your code will only return full matches. You can just trim the first and last "s here with .map {$0.trimmingCharacters(in: ["\""])}, as the regex only matches one quote at the start and end:

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

    Here is the regex demo.

    Alternatively, access Group 1 value by appending (at: 1) after $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"]
    
    0 讨论(0)
提交回复
热议问题