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"]
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…