问题
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:
title_identifier = "Hi \"how\", are \"you\"";
I would like to bold out "how" and "you" in this string by finding the range of these words. So I am trying to fetch these quoted words out of the string and the result would be an array containing "how" and "you" or their 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, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
matches(for: "(?<=\")[^\"]*(?=\")", in: str)
The result is: ["how", ", are ", "you"]
rather than ["how","you"]
. I think this regex needs some addition to allow it to search for next quote once two quotes are found, so to avoid the words in between quotes.
回答1:
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"]
来源:https://stackoverflow.com/questions/57852915/find-multiple-quoted-words-in-a-string-with-regex